Home >Backend Development >PHP Tutorial >Public properties and private properties of PHP classes and objects_PHP tutorial
This article gives you a simple example of the usage of public attributes and private attributes in PHP classes and objects. Friends who need to know more can refer to it.
Private attribute
Properties that define private attributes can only be used in this class, and can be called through $this-> in this class. However, referencing private properties externally will result in an error.
Example:
The code is as follows
|
Copy code
|
||||||||
class People{
private $name="li ming";
}
$p=new People(); echo $p->name; ?>
Note: Fields with private properties cannot be used in subclasses.
Public properties In PHP class operations, when declaring fields, use public, private, protected, final, const, and static to describe the scope of the object's data elements. These characters are called limited access control characters. Attributes declared with the keyword public are called public attributes and can be read and modified freely inside and outside the class. This is obviously not safe enough and destroys the encapsulation characteristics of the class.
|
The code is as follows | Copy code
|