Visibility and Getters
Solidity có 4 loại Visibility cho Function và State Variables:
external: External Function là một phần của Contract Interface, nghĩa là nó có thể được gọi bởi Contract khác
public: Public Function là một phần của Contract Interface, nó có thể được gọi trong nội bộ hoặc thông qua message. Đối với Public Variable, nó sẽ được tự động sinh ra một Getter Function.
internal: Functions và State Varibales chỉ có thể truy cập trong bản thân Contract hoặc Contract có nguồn gốc từ Contract chỉ định visibility
private: Chỉ có Contract định nghĩa Visibility này mới có thể truy cập
Ví dụ:
Contract D có thể gọi c.getData() để lấy biến data của Contract C nhưng không thể gọi f().
Contract E vì có nguồn gốc từ Contract C nên có thể gọi compute()
pragma solidity >=0.4.0 <0.7.0;
contract C {
uint private data;
function f(uint a) private pure returns(uint b) { return a + 1; }
function setData(uint a) public { data = a; }
function getData() public view returns(uint) { return data; }
function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
}
// This will not compile
contract D {
function readData() public {
C c = new C();
uint local = c.f(7); // error: member `f` is not visible
c.setData(3);
local = c.getData();
local = c.compute(3, 5); // error: member `compute` is not visible
}
}
contract E is C {
function g() public {
C c = new C();
uint val = compute(3, 5); // access to internal member (from derived to parent contract)
}
}Getter
Compiler sẽ tự động tạo getter function cho tất cả Public State Variable (chỉ getter, không tự động tạo setter)
Ví dụ:
Compiler tự động sinh ra getter là function data() cho public state variable là data
Last updated
Was this helpful?