"In general, it is more logical to define the attributes of a class as private."
However, read and assign operations on attributes are very frequent, therefore, in PHP5, two functions "__get ()" and "__set ()" are predefined to get and assign their properties, and to check the "__isset ()" of the property and the Method "__unset ()" for deleting the property.
We have set and get methods for each attribute, in PHP5 we provide methods for setting values and fetching values for attributes, "__set ()" and "__get ()", two methods that are not by default, but rather as we add them to the class by hand, such as the construction method (__ Construct ()), just as the class is added to exist, you can add the two methods in the following way, and of course you can add them in a personal style: "
<?php
//Interceptor Use
class computer{
private $name;
Private $price;
Private $cpu;
Private $clocked;
Interceptor Assignment Public
function __set ($key, $value) {
//So: $key =name $value = "Lenovo" There are: $this->name= "Lenovo" return
$this-> $key = $value;
}
Interceptor value public
function __get ($key) {
if isset ($key)) {
//Then: $key =name $this->name so naturally return. " Lenovo "return
$this-> $key;
} else {return
NULL;
}
}} It is precisely because of the interceptor exists, can be so used
$computer =new computer ();
$computer->name= "Association";
$computer->price=5600;
$computer->cpu= "eight cores";
$computer->clocked= "1600hz";
echo $computer->name;
echo $computer->price;
echo $computer->cpu;
echo $computer->clocked;
The above is a small series for everyone to talk about the PHP Interceptor __set () and __get () the understanding and use of all content, I hope that we support cloud Habitat Community ~