Explanation of attributes of php class

怪我咯
Release: 2023-03-11 19:54:02
Original
2056 people have browsed it

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';
}
Copy after login

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; //内部访问私有属性
    }
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template