php 魔术方法
__tostring 将对象当字符串输出
__invoke 将对象当方法输出
例子:
class Test{
public function __tostring(){
return 'this is test
';
';
}
public function __invoke($x){
echo 'params is methed '.$x;
}
}
$obj = new Test();
echo $obj;
$obj(6);
方法的重载:当类中没有此方法时候调用的魔术方法
$name:方法的名称
$arguments:方法中参数组成的数组
__call($name,$arguments)
__callStatic($name,$arguments)
例子:
class Test{
public function __call($name,$arguments){
echo "call===".$name.'====with parameters:'.implode(',',$arguments)."
";
";
}
public static function __callStatic($name,$array){
echo "static calling===".$name.'====with parameters:'.implode(',',$array)."\n";
}
}
$obj = new Test();
$obj->runTest('param');
Test::runTest('param1','param2');
属性重载:对未定义属性的操作
__get($name)
__set($name,$value)
__isset($name)
__unset($name)
例子
class Test{
public function __get($name){
echo 'Getting the property '.$name.'
';
';
}
public function __set($name,$value){
echo 'Setting the property '.$name.' to value '.$value.'
';
';
}
public function __isset($name){
echo "__setting invoke
";
";
return true;
}
public function __unset($name){
echo "Unset property {$name}
";
";
}
}
$obj = new Test();
$obj->classname;
$obj->classname = 'TestValue';
echo '$obj->classname is set?'.isset($obj->classname).'
';//取决返回值是true还是false
';//取决返回值是true还是false
unset($obj->classname);
__clone:只想修改当前类的某些数据,不影响当前类的时候调用
例子
class Test{
public $name;
public function __clone(){//当权限为privite和protected权限时,外部不可用clone函数
$this->name = 'TBD';
}
}
$obj = new Test();
$obj->name = 'james';
echo $obj->name.'
';
';
$obj2 = clone $obj;
echo 'before set up:$obj2: '.$obj2->name.'
';
';
$obj2->name = 'james2';
echo 'james: '.$obj->name.'
';
';
echo 'james2: '. $obj2->name.'
';
';

浙公网安备 33010602011771号