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.
public
: Apublic
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.private
: Aprivate
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.internal
: Aninternal
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
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
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
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