有人能帮我更容易地理解魔术方法吗?
我知道魔术方法在代码的某个点被触发,但我不明白它们触发的具体时机。例如,对于 __construct(),它们在创建类的对象时触发,传递的参数是可选的。
请告诉我何时会特别触发 __get()
、__set()
、__isset()
、__unset()
。如果提到其他魔术方法,那就更好了。
有人能帮我更容易地理解魔术方法吗?
我知道魔术方法在代码的某个点被触发,但我不明白它们触发的具体时机。例如,对于 __construct(),它们在创建类的对象时触发,传递的参数是可选的。
请告诉我何时会特别触发 __get()
、__set()
、__isset()
、__unset()
。如果提到其他魔术方法,那就更好了。
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()
方法仅适用于私有变量。
以双下划线 (__ ) 开头的 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
}
}