The access level of a PHP function specifies the code access level: Public: Can be accessed by any code. Protected: Accessible by the same class or subclasses. Private: Accessible only by the class in which the function is defined.
In PHP, the access level for a function specifies which code can access the function. You can control the visibility of a function by using access modifiers. The following are the access levels specified in PHP:
1. Public
Example:
public function publicFunction() { // 函数代码 }
2. Protected
Example:
protected function protectedFunction() { // 函数代码 }
3. Private
Example:
private function privateFunction() { // 函数代码 }
Practical Case
Consider the following example where we define in different classes defines functions with different access levels:
class ParentClass { public function publicFunction() { echo "Public function in parent class"; } protected function protectedFunction() { echo "Protected function in parent class"; } private function privateFunction() { echo "Private function in parent class"; } } class ChildClass extends ParentClass { public function accessFunctions() { $this->publicFunction(); $this->protectedFunction(); // 错误:对私有函数无访问权限 $this->privateFunction(); } } // 实例化子类 $child = new ChildClass(); // 调用公共和受保护的函数 $child->publicFunction(); $child->protectedFunction();
In this example, ParentClass
defines functions with different access levels, while ChildClass
inherits ParentClass
. The accessFunctions()
method in ChildClass
has access to public and protected functions but not to private functions.
The above is the detailed content of How to specify access level for PHP functions?. For more information, please follow other related articles on the PHP Chinese website!