Variable Scope
There are three types of variable scopes in Solidity:
1. Public
Public variables are accessible from within the contract and can be accessed from external contracts as well. Solidity automatically generates a getter function for public state variables.
Syntax:
<type> public <variable_name>;
2. Private
Private variables are only accessible within the contract they are defined in. They are not accessible from derived contracts or external contracts.
Syntax:
<type> private <variable_name>;
3. Internal
Internal variables are accessible within the contract they are defined in and derived from contracts. They are not accessible from external contracts.
Syntax:
<type> internal <variable_name>;
Below is the Solidity program to implement the variable scope:
Solidity
// Solidity program to implement // the variable scope // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VariableScopeExample { uint public publicVar = 1; uint private privateVar = 2; uint internal internalVar = 3; function getPrivateVar() public view returns (uint) { return privateVar; } } contract DerivedContract is VariableScopeExample { function getInternalVar() public view returns (uint) { return internalVar; } } |
Output: The publicVar can be accessed using the automatically generated getter function publicVar(). The privateVar can be accessed using the getPrivateVar() function from within the VariableScopeExample contract. The internalVar can be accessed by the getInternalVar() function in the derived contract DerivedContract.
Solidity – Variable Scope
Variable scope is an essential concept in Solidity, the programming language for Ethereum smart contracts. Solidity has various types of variables with different scopes, such as local, state, and global variables.