理解PHP中的魔术方法

时间:2013-10-19 04:43:32

标签: php oop magic-methods

有人帮助我以更简单的方式理解魔法。

我知道魔术方法是在代码的某个点触发的,我不明白的是它们被触发的点。 就像__construct()一样,它们是在创建类的对象时触发的,要传递的参数是可选的。

请特别在__get()__set()__isset()__unset()被触发时告诉我。如果说明任何其他魔术方法,将会非常有用。

2 个答案:

答案 0 :(得分:2)

PHP的魔术方法都以“__”开头,只能在类中使用。我试着在下面写一个例子。

class Foo
{
    private $privateVariable;
    public $publicVariable;

    public function __construct($private)
    {
        $this->privateVariable = $private;
        $this->publicVariable = "I'm public!";
    }

    // triggered when someone tries to access a private variable from the class
    public function __get($variable)
    {
        // You can do whatever you want here, you can calculate stuff etc.
        // Right now we're only accessing a private variable
        echo "Accessing the private variable " . $variable . " of the Foo class.";

        return $this->$variable;
    }

    // triggered when someone tries to change the value of a private variable
    public function __set($variable, $value)
    {
        // If you're working with a database, you have this function execute SQL queries if you like
        echo "Setting the private variable $variable of the Foo class.";

        $this->$variable = $value;
    }

    // executed when isset() is called
    public function __isset($variable)
    {
        echo "Checking if $variable is set...";

        return isset($this->$variable);
    }

    // executed when unset() is called
    public function __unset($variable)
    {
        echo "Unsetting $variable...";

        unset($this->$variable);
    }
}

$obj = new Foo("hello world");
echo $obj->privateVariable;     // hello world
echo $obj->publicVariable;      // I'm public!

$obj->privateVariable = "bar";
$obj->publicVariable = "hi world";

echo $obj->privateVariable;     // bar
echo $obj->publicVariable;      // hi world!

if (isset($obj->privateVariable))
{
    echo "Hi!";
}

unset($obj->privateVariable);

总之,使用这些魔术方法的一个主要优点是,如果您想要访问类的私有变量(这违反了许多编码实践),但它确实允许您为特定事物的时间分配操作执行;即设置变量,检查变量等

请注意,__get()__set()方法仅适用于私有变量。

答案 1 :(得分:0)

以双下划线开头的PHP函数 - __ - 在PHP中称为魔术函数(和/或方法)。它们是始终在类中定义的函数,并不是独立的(在类之外)函数。 PHP中可用的神奇功能是:

  

__ construct(),__ desttruct(),__ call(),__ callStatic(),__ get(),__ set(),__ isset(),__ unit(),_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ,__ set_state(),__ clone()和__autoload()。

现在,这是一个具有__construct()魔术功能的类的示例:

class Animal {

    public $height;      // height of animal  
    public $weight;     // weight of animal

    public function __construct($height, $weight) 
    {
        $this->height = $height;  //set the height instance variable
        $this->weight = $weight; //set the weight instance variable
    }
}