有人帮助我更轻松地理解魔术方法。了解PHP中的魔术方法
我知道魔法方法是在代码的某个点触发的,我不明白的是它们被触发的点。 就像在__construct()的情况下一样,它们在创建类的对象时触发,并且要传递的参数是可选的。
请告诉我什么时候__get()
,__set()
,__isset()
,__unset()
是特别触发的。如果说到其他任何魔法方法,这将是很有帮助的。
有人帮助我更轻松地理解魔术方法。了解PHP中的魔术方法
我知道魔法方法是在代码的某个点触发的,我不明白的是它们被触发的点。 就像在__construct()的情况下一样,它们在创建类的对象时触发,并且要传递的参数是可选的。
请告诉我什么时候__get()
,__set()
,__isset()
,__unset()
是特别触发的。如果说到其他任何魔法方法,这将是很有帮助的。
以双下划线开头的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
}
}
这看起来像一个复制粘贴,请将来源归功于信用。它不是你自己的答案。 –
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()
方法将只适用于私有变量。
我想你会发现这个主题回答了一些你的问题: http://stackoverflow.com/questions/4713680/php-get-and-set-magic-methods – Marc