Modifiers

In Solidity, variables can be declared with different visibility modifiers, such as public, private, and internal. These modifiers determine how the variables can be accessed within the contract.

  1. public: A public variable can be accessed both from inside and outside of the contract. Solidity will automatically generate a getter function for the variable, allowing other contracts or clients to read its value.

  2. private: A private variable can only be accessed from within the contract where it is defined. It is not visible to other contracts or clients, and Solidity does not generate a getter function for it.

  3. internal: An internal variable can be accessed from within the contract where it is defined and any contracts that inherit from it. It is not visible to other contracts or clients, and Solidity does not generate a getter function for it.

These visibility modifiers help to control access to a contract's data and ensure that it is used appropriately.

Examples

Public

pragma solidity ^0.8.0;

contract MyContract {
    uint256 public myPublicVar = 10;
}

In this example, myPublicVar is a public variable that can be accessed and read by any external party. It has an initial value of 10 and can be changed by any external party that interacts with the contract.

Private

pragma solidity ^0.8.0;

contract MyContract {
    uint256 private myPrivateVar = 20;

    function getMyPrivateVar() public view returns (uint256) {
        return myPrivateVar;
    }
}

In this example, myPrivateVar is a private variable that can only be accessed and read by the contract itself. It has an initial value of 20 and can only be accessed through the public getMyPrivateVar() function.

Internal

pragma solidity ^0.8.0;

contract MyContract {
    uint256 internal myInternalVar = 30;
}

contract MyOtherContract is MyContract {
    function getMyInternalVar() public view returns (uint256) {
        return myInternalVar;
    }
}

In this example, myInternalVar is an internal variable that can be accessed and read by any contract that inherits from MyContract. It has an initial value of 30 and can be accessed through the public getMyInternalVar() function in the MyOtherContract contract.

Last updated