Setting properties with the _ _set () method
boolean __set ([string property_name], [mixed value_to_assign])
I wrote an easy-to-understand
<?PHPclassemployee{var $name; function__set ($propName,$propValue) { Echo' $name = '.$this->name. ' <br/> '; Echo' $propName = '.$propName. ' <br/> '; Echo' $propValue = '.$propValue. "<br/>"; $this-$propName=$propValue; } }$employee=NewEmployee ();$employee->name = "Mario";$employee->title = "Exective Chef";Echo $employee-title;//Output//$name =mario//$propName = title//$propValue = exective Chef
__set () method is the default, I tested, I do not write __set () method, can also implement
$employee->sex = ' M ';
Echo $employee->sex;
The __set () method can limit the setting of some properties, such as:
<?PHPclassemployee{var $name; function__set ($propName,$propValue) { if($propName= = ' age ') { if($propValue< 18 | |$propValue> 60) { $this-$propName=NULL; } Else { $this-$propName=$propValue; } } Else { $this-$propName=$propValue; } }}$employee=NewEmployee ();$employee->name = "Mario";$employee->age = "17";$employee->page = 1;Echo' name = '.$employee->name. ' <br/> ';Echo' Age = '.$employee->age. ' <br/> ';Echo' page = '.$employee-page;//output employee is less than 18 or greater than 60 when age=null//name = mario//Age =//page = 1
Get Properties with _ _get () method
boolean __get ([string property_name])
Test
Conclusion:
__set () and __get () are not only too long when the attributes are present. Test examples are as follows
<?PHPclassemployee{ Public $name; Public $city; protected $wage; function__set ($propName,$propValue) { Echo"__set called!<br/>";$this-$propName=$propValue; } function__get ($propName) { Echo"__get called!<br/>"; $vars=Array( "Name", "City" ); if(In_array($propName,$vars)) { return $this-$porpName; } Else { return"No such variable!"; } } }$employee=NewEmployee ();$employee->name = "Mario";$employee->city = "Shan";Echo $employee->name. "<br/>";Echo $employee-City . "<br/>";//Output//mario//Shan
Under Add code,
$employee->age =; Echo $employee->age. "<br/>"; // Output//__set called!// Echo $employee->sex. "<br/>"; // Output//__get called!//No such variable!
If you add sex to the $vars array, the program error!
Look down feel no bright spots, not used up.
"PHP and MySQL Program design" chapter sixth