3

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

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

请告诉我什么时候 特别触发__get(), __set(), __isset(), 。__unset()如果说明任何其他魔术方法会很有帮助。

4

2 回答 2

3

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()仅适用于私有变量。

于 2013-10-19T05:09:32.393 回答
0

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

__construct()、__destruct()、__call()、__callStatic()、__get()、__set()、__isset()、__unset()、__sleep()、__wakeup()、__toString()、__invoke()、__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
    }
}
于 2013-10-19T04:45:23.860 回答