AttributeThe declaration starts with the keywords public, protected or private, followed by an ordinary variable declaration. The variable of the attribute can be set to an initialized default value, and the default value must be a constant.
class Car { //定义公共属性 public $name = '汽车'; //定义受保护的属性 protected $corlor = '白色'; //定义私有属性 private $price = '100000'; }
The default is public and can be accessed externally. Generally, the properties or methods of an object are accessed through the ->Objectoperator. For static properties, use ::double colon to access. When called inside a class member method, you can use the $this pseudo variable to call the properties of the current object.
$car = new Car();
echo $car->name; //Call the properties of the object
echo $car->color; // Error Protected properties do not allow external calls
echo $car->price; //Error Private properties do not allow external calls
Protected properties and private properties do not allow external calls. It can be called inside the member method of the class.
class Car{ private $price = '1000'; public function getPrice() { return $this->price; //内部访问私有属性 } }
The above is the detailed content of Explanation of attributes of php class. For more information, please follow other related articles on the PHP Chinese website!