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, and can be called through $ this-> in this class. If you reference a private attribute externally, an error is returned.
Instance:
The Code is as follows: |
Copy code |
<? Php 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 and can be freely read and modified inside and outside the class. This is obviously not safe enough, undermining the class encapsulation characteristics.
If the field is not declared, the default value is public.
Instance:
The Code is as follows: |
Copy code |
<? Php Class Man { Public $ name = "John";/* set public attributes */ Var $ age = 20; } $ A = new Man (); Echo $ a-> name. "<br> "; 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.
Instance:
The Code is as follows: |
Copy code |
<? Php 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. "<br> "; Echo $ a-> age; ?> |