【问题标题】:Understanding magic methods in PHP [duplicate]了解 PHP 中的魔术方法 [重复]
【发布时间】:2013-10-28 01:14:48
【问题描述】:

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

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

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

【问题讨论】:

标签: php oop magic-methods


【解决方案1】:

以双下划线开头的 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
    }
}

【讨论】:

  • 这看起来像复制粘贴,请正确注明出处。这不是你自己的答案。
【解决方案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() 方法仅适用于私有变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2010-10-27
    相关资源
    最近更新 更多