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
代码如下 |
复制代码 |
class People{
private $name="li ming";
}
$p=new People();
echo $p->name;
?>
|
|
Copy code
|
class People{
private $name="li ming";
}
$p=new People();
echo $p->name;
?>
Note: Fields with private properties cannot be used in subclasses.
代码如下 |
复制代码 |
class Man{
public $name="John"; /* 设定公共属性 */
var $age=20;
}
$a=new Man();
echo $a->name." ";
echo $a->age;
?>
|
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.
代码如下 |
复制代码 |
class Man{
public $name="John";
var $age;
}
$a=new Man();
$a->name="Tom"; /* 改变属性值 */
$a->age=20; /* 赋予属性值 */
echo $a->name." ";
echo $a->age;
?>
|
If the field is not declared, it defaults to public. |
Example:
The code is as follows
|
Copy code
class Man{
public $name="John"; /* Set public attributes */
var $age=20;
}
$a=new Man();
echo $a->name." ";
echo $a->age;
?>
Change attribute values
If the attribute is declared as public, the value of the attribute can be changed as needed or assigned an undefined attribute value when called externally.
Example:
The code is as follows
|
Copy code
|
class Man{<🎜>
public $name="John"; <🎜>
var $age;<🎜>
}<🎜>
$a=new Man();<🎜>
$a->name="Tom"; /* Change attribute value */
$a->age=20; /* Assign attribute value */
echo $a->name." ";
echo $a->age;
?>
http://www.bkjia.com/PHPjc/628817.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628817.htmlTechArticleThis article gives you a simple example of the usage of public attributes and private attributes in PHP classes and objects, if you need to understand Friends can refer to it. Private attributes define attributes that are private...
|
|
|