Home > Backend Development > PHP Tutorial > How to specify access level for PHP functions?

How to specify access level for PHP functions?

WBOY
Release: 2024-04-16 15:51:01
Original
414 people have browsed it

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.

PHP 函数的访问权限级别如何指定?

Access level specification for PHP functions

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

  • The public access level allows any code to access the function, regardless of where it is In the same script or in different scripts.

Example:

public function publicFunction() {
  // 函数代码
}
Copy after login

2. Protected

  • The protected access level allows Access this function in the same class or its subclasses.

Example:

protected function protectedFunction() {
  // 函数代码
}
Copy after login

3. Private

  • Private access level is only allowed when defined Access the function in the function's class.

Example:

private function privateFunction() {
  // 函数代码
}
Copy after login

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template