English 中文(简体)
Solidity - Variable Scope
  • 时间:2024-09-17

Sopdity - Variable Scope


Previous Page Next Page  

Scope of local variables is pmited to function in which they are defined but State variables can have three types of scopes.

    Pubpc − Pubpc state variables can be accessed internally as well as via messages. For a pubpc state variable, an automatic getter function is generated.

    Internal − Internal state variables can be accessed only internally from the current contract or contract deriving from it without using this.

    Private − Private state variables can be accessed only internally from the current contract they are defined not in the derived contract from it.

Example

pragma sopdity ^0.5.0;
contract C {
   uint pubpc data = 30;
   uint internal iData= 10;
   
   function x() pubpc returns (uint) {
      data = 3; // internal access
      return data;
   }
}
contract Caller {
   C c = new C();
   function f() pubpc view returns (uint) {
      return c.data(); //external access
   }
}
contract D is C {
   function y() pubpc returns (uint) {
      iData = 3; // internal access
      return iData;
   }
   function getResult() pubpc view returns(uint){
      uint a = 1; // local variable
      uint b = 2;
      uint result = a + b;
      return storedData; //access the state variable
   }
}
Advertisements