+ -
当前位置:首页 → 问答吧 → 魔术方法详解2

魔术方法详解2

时间:2008-11-06

来源:互联网

上一节http://bbs.phpchina.com/thread-88774-1-1.html已经说过了__sleep()和__wakeup(),今天再来解说其他的魔术方法吧!

__toString
__toString方法是在一个对象被强行转换成字符串时自动调用的,好像echo一个对象时就会调用。看以下例子:

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

输出:Hello


__set() , __get()


   
当我们对原先不存在的成员变量进行设置时,__set()方法会自动调用,其参数是变量名及相应的值。看例子:

<?php
class Data_Hloder {
    public function __set($name, $value) {
        echo '__set() method is call.';
    }
}

$data = new Data_Hloder();
$data->name = "Tony";
?>

输出:__set() method is call.

而__get()方法是当企图访问不存在的成员变量时会自动调用。看例子:

<?php
class Data_Hloder {
    public function __set($name, $value) {
        echo '__set() method is call.';
    }
    public function __get($name) {
        echo '__get() method is call.';
    }
}

$data = new Data_Hloder();
$data->name = "Tony";
echo $data->name;
?>

输出:__set() method is call.__get() method is call.

这两个方法非常有用,可以利用它们实现动态设置成员变量,看例子:
[php]
<?php
class Data_Hloder {
    private $data;
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
    public function __get($name) {
        if(isset($this->data[$name])) {
            return $this->data[$name];
        }
    }
}

$data = new Data_Hloder();
$data->name = "liexusong"; //我们为一个不存在的成员变量设置值,会自动调用__set()方法,把$this->data['name']设为liexusong
echo $data->name; //访问不存在的name变量,自动调用__get()方法,返回$this->data['name']的值,即为liexusong
?>
[/php]
输出:liexusong

作者: liexusong   发布时间: 2008-11-06

上面的代码,由于改变了类中私有变量的类型,我觉得这样用有不托之处,楼主的data最后变成了一个数组,
应该在不改变原来内部变量的情况下进行动态添加:
<?php
class Data_Hloder {
    private $data;
    public function __set($name, $value) {
        $this->$name = $value;

        
    }
    public function __get($name) {
        if(isset($this->$name)) {
            return $this->$name;
        }
    }
}

$data = new Data_Hloder();
$data->name = "liexusong";
echo $data->name;

$data->age = 27;
echo $data->age;
print_r($data);
?>

输出:

liexusongliexData_Hloder Object
(
    [data:private] =>
    [name] => liexusong
    [age] => 27
)


而且这里面的_set 和 _get对任何类都可以通用,不用更改任何东西。

作者: sanyawa   发布时间: 2008-12-01