Home > Article > Backend Development > What are the access control levels for PHP functions?
There are three access control levels for PHP functions: public, protected, and private. Public functions can be accessed from anywhere, protected functions are only accessible to its own class and subclasses, and private functions are only accessible to its own class. When modifying the access control level, just add the corresponding keywords before the function declaration, such as public function, protected function, private function.
Access control level of PHP function
The access control level of PHP function determines which parts of the function can be accessed. It allows us to restrict access to functions, thereby improving the maintainability and security of our code.
Access control levels
There are three access control levels in PHP:
Syntax
When modifying the access control level, just add the corresponding keyword before the function declaration.
// public 函数 public function myPublicFunction() { // ... } // protected 函数 protected function myProtectedFunction() { // ... } // private 函数 private function myPrivateFunction() { // ... }
Practical case
Suppose we have a class User
for storing user data. We want to allow access to user data only through the public methods of this class. To achieve this, we will set the function that gets user data to protected:
class User { protected $name; protected $email; public function getName() { return $this->name; } public function getEmail() { return $this->email; } }
Now other classes can access getName()
and # through the User
object ##getEmail() method, but there is no direct access to the
$name and
$email properties.
Note
.
The above is the detailed content of What are the access control levels for PHP functions?. For more information, please follow other related articles on the PHP Chinese website!