用_ _set()方法设置属性
boolean __set([string property_name] , [mixed value_to_assign])
自己写了个容易理解的
<?php class Employee { var $name; function __set($propName, $propValue) { echo ‘$name =‘ . $this->name . ‘<br/>‘; echo ‘$propName = ‘ . $propName . ‘<br/>‘; echo ‘$propValue = ‘ . $propValue . "<br/>"; $this->$propName = $propValue; } } $employee = new Employee(); $employee->name = "Mario"; $employee->title = "Exective chef"; echo $employee->title; //输出 // $name =Mario // $propName = title // $propValue = Exective chef
__set()方法是默认的,我测试了一下,我不写__set()方法,也可以实现
$employee->sex = ‘M‘;
echo $employee->sex;
__set()的方法可以限制一些属性的设置,比如:
<?php class Employee { 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 = new Employee(); $employee->name = "Mario"; $employee->age = "17"; $employee->page = 1; echo ‘name = ‘ . $employee->name . ‘<br/>‘; echo ‘age = ‘ . $employee->age . ‘<br/>‘; echo ‘page = ‘ . $employee->page; //输出 雇员的年龄小于18或大于60的时候age=null // name = Mario // age = // page = 1
用 _ _get()方法获取属性
boolean __get([string property_name])
测试
结论:
当属性存在的时候,__set()和__get()是不仅过的。测试例子如下->
<?php class Employee { 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 = new Employee(); $employee->name = "Mario"; $employee->city = "shan"; echo $employee->name . "<br/>"; echo $employee->city . "<br/>"; // 输出 // Mario // shan
在下面加入下的代码->
$employee->age = 20; echo $employee->age . "<br/>"; // 输出 // __set called! // 20 echo $employee->sex . "<br/>"; //输出 // __get called! // No such variable!
如果在$vars数组中加入sex的话,程序报错!
看下来感觉没什么亮点,用不起来。
时间: 2024-10-20 11:38:21