Modifiers (Functions)

In Solidity, functions can have visibility modifiers that determine where they can be called from. The four visibility modifiers are:

  1. Public: Functions marked as public can be called from within the contract itself, as well as from outside the contract. They are part of the contract's interface, which means that they can be accessed by other contracts and external accounts.

  2. Private: Functions marked as private can only be called from within the contract itself. They are not part of the contract's interface and cannot be accessed by other contracts or external accounts.

  3. Internal: Functions marked as internal can be called from within the contract itself, as well as from within contracts that inherit from it. They are not part of the contract's interface and cannot be accessed by external accounts.

  4. External: Functions marked as external can only be called from outside the contract. They are part of the contract's interface and can be accessed by other contracts and external accounts, but cannot be called from within the contract itself.

These modifiers allow Solidity developers to control the visibility and accessibility of their functions, which is important for security and contract design.

Examples

Public function:

contract MyContract {
    uint public myNumber;
    
    function setNumber(uint _number) public {
        myNumber = _number;
    }
}

Private function:

contract MyContract {
    uint private myNumber;
    
    function setNumber(uint _number) private {
        myNumber = _number;
    }
}

Internal function:

contract MyContract {
    uint internal myNumber;
    
    function setNumber(uint _number) internal {
        myNumber = _number;
    }
}

contract ChildContract is MyContract {
    function setMyNumber(uint _number) external {
        setNumber(_number);
    }
}

External function:

contract MyContract {
    uint public myNumber;
    
    function setNumber(uint _number) external {
        myNumber = _number;
    }
}

Last updated