Home  >  Article  >  Backend Development  >  How to operate the properties of objects in php

How to operate the properties of objects in php

怪我咯
怪我咯Original
2017-06-28 13:58:375959browse

In java, we need to encapsulate attributes, which is also one of the major properties of Object-oriented. After we encapsulate the attributes in java, we may encapsulate each An attribute is set with set and get methods, so that the attribute can be accessed. In PHP, the same principle is the same, but in PHP, there is no need to set all objects. It has a get()set() by defaultMagic method, provides us with easy access to private attributes, as follows:

class person{
private $name;//这是private类型的属性,我们直接使用对象->属性是访问不到的。我们需要添加魔术方法get()才可以访问
private $age;
private function  get($proname){//get方法是系统调用的,添加此魔术方法之后,我们直接对象->属性名获取值时,系统会自动地调用这个方法,但是我们必须添加参数,以及添加方法体。
return $this->$proname;
}
private function  set($proname,$value){//设置参数,我们需要设置两个参数
echo "set<br>";
$this->$proname=$value;
}
public function  construct($name,$age){
$this->name=$name;
$this->age=$age;
}
}

Note the following points:

After we encapsulate the class attributes, if the attribute is set to private If so, then directly: Object-> The attribute cannot be accessed. We need to add the get() method to access it

If our attribute is set to private, we can directly: Object-> Attribute = value also cannot be set. We also need to add the _set() method to access it.

Implementation:

private function  get($proname){
return $this->$proname;
}
private function  set($proname,$value){
$this->$proname=$value;
}

The above is the detailed content of How to operate the properties of objects in php. 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