A brief discussion on the understanding and use of __set() and __get() in PHP interceptors_php examples

WBOY
Release: 2023-03-03 06:44:01
Original
1070 people have browsed it

"Generally speaking, always define the attributes of a class as private, which is more in line with realistic logic.

However, reading and assigning operations to attributes are very frequent, so in PHP5, two functions "__get()" and "__set()" are predefined to obtain and assign their attributes, as well as " __isset()" and the method to delete attributes "__unset()".

We have set and get methods for each attribute. PHP5 provides us with special methods for setting and getting values ​​for attributes, "__set()" and "__get()". These two methods This method does not exist by default, but we add it to the class manually. Like the constructor method (__construct()), it will only exist if it is added to the class. You can add these two methods in the following way. Of course, You can add it according to your personal style: "

<&#63;php
//拦截器的使用
class Computer{
private $name;
private $price;
private $cpu;
private $clocked;

//拦截器之赋值
public function __set($key,$value){
//那么:$key=name $value="联想" 则有: $this->name="联想"
return $this->$key=$value;
}

//拦截器之取值
public function __get($key){
if (isset($key)){
//那么: $key=name 则$this->name 所以自然就return了"联想"
return $this->$key;
}else {
return NULL;
}
}
}
//正是因为的拦截器存在,才能如此用
$computer=new Computer();
$computer->name="联想";
$computer->price=5600;
$computer->cpu="八核";
$computer->clocked="1600hz";

echo $computer->name;
echo $computer->price;
echo $computer->cpu;
echo $computer->clocked;
Copy after login

The above is the entire content that the editor has brought to you on the understanding and use of __set() and __get() in PHP interceptors. I hope you will support Script Home~

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!