This article provides a simple example to illustrate the usage of public and private attributes of php classes and objects. if you need to know, you can refer to private attributes to define private attributes) only
This article provides a simple example to illustrate the usage of public and private attributes of php classes and objects. For more information, see.
Private attributes
Attributes that define private attributes can only be used in this class. in this class, you can use $ this-> to call these attributes. if you reference private attributes externally, an error is returned.
The instance code is as follows:
-
- Class People {
- Private $ name = "li ming ";
- }
- $ P = new People ();
- Echo $ p-> name;
- ?>
Note: fields with private attributes cannot be used in subclass.
Public attributes
In php operations, when declaring a field, public, private, protected, final, const, and static are used to describe the scope of the data element of the object. such characters are called restricted access control characters.
Attributes with the keyword public declaration are called public attributes, which can be freely read and modified inside and outside the class. this is obviously not safe enough and breaks the class encapsulation characteristics.
If the field is not declared, the default value is public.
The instance code is as follows:
-
- Class Man {
- Public $ name = "John";/* set public attributes */
- Var $ age = 20;
- }
- $ A = new Man ();
- Echo $ a-> name ."
";
- Echo $ a-> age;
- ?>
Change attribute value
If the attribute is declared as public, you can change the attribute value or assign the undefined attribute value as needed during external calls.
The instance code is as follows:
-
- Class Man {
- Public $ name = "John ";
- Var $ age;
- }
- $ A = new Man ();
- $ A-> name = "Tom";/* Change the attribute value */
- $ A-> age = 20;/* assign attribute values */
- Echo $ a-> name ."
";
- Echo $ a-> age;
- ?>