Home  >  Article  >  Backend Development  >  Explanation of attributes of php class

Explanation of attributes of php class

怪我咯
怪我咯Original
2017-06-28 13:25:452002browse

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!

Statement:
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