什么是魔术方法以及如何在PHP中使用它们?
PHP魔术方法是在满足某些条件时自动调用的特殊方法。 PHP中有几种神奇的方法。每一种魔法方法都遵循一定的规则——
- 每个魔术方法都以双下划线 (__) 开头。
- 它们是预定义的,既不能创建也不能删除。
- 魔术方法具有保留名称,它们的名称不应用于其他目的。
- 当满足某些条件时,会自动调用魔术方法。
Method Names | Return types | Condition of calling |
__construct() | NaN | This method gets called automatically every time the object of a particular class is created. The function of this magic method is the same as the constructor in any OOP language. |
__destruct() | NaN | As the name suggests this method is called when the object is destroyed and no longer in use. Generally at the end of the program and end of the function. |
__call($name,$parameter) | Not mandatory | This method executes when a method is called which is not defined yet. |
__toString() | String | This method is called when we need to convert the object into a string. For example: echo $obj; The $obj->__toString(); will be called magically. |
__get($name) | NaN | This method is called when an inaccessible variable or non-existing variable is used. |
__set($name , $value) | NaN | This method is called when an inaccessible variable or non-existing variable is written. |
__debugInfo() | array | This magic method is executed when an object is used inside var_dump() for debugging purposes. |
以下是代码片段和示例,以更好地理解魔术方法。
__construct() 方法:在下面的示例中,MagicMethod 类有一个魔术方法__construct() ,每次创建 MagicMethod 类的新对象时都会调用它。
PHP
PHP
PHP
" . $name."\n";
echo "Parameters provided\n";
print_r($parameters);
}
}
// Instantiating MagicMethod
$obj = new MagicMethod();
$obj->hello("Magic" , "Method");
?>
PHP
PHP
value;
?>
PHP
value = "Hello";
?>
PHP
"value");
}
}
$obj = new MagicMethod();
var_dump($obj);
?>
This is the construct magic method
__destruct() 方法:在下面的示例中,MagicMethod 类有一个魔术方法__destruct() ,当 MagicMethod 的对象销毁时会自动调用该方法。
PHP
This destruct magic method gets called
when object destroys
__call($name, $parameters) 方法:当调用尚未定义的方法或属性时,将调用此方法。
这个方法有两个参数:
- $name:这包含被调用的方法的名称。
- $parameters:这是为该方法提供的参数数组。
PHP
" . $name."\n";
echo "Parameters provided\n";
print_r($parameters);
}
}
// Instantiating MagicMethod
$obj = new MagicMethod();
$obj->hello("Magic" , "Method");
?>
Name of method =>hello
Parameters provided
Array
(
[0] => Magic
[1] => Method
)
__toString() 方法:当对象被视为字符串时调用此方法。此方法对于将对象表示为字符串也很有用。
PHP
You are using MagicMethod object as a String
__get($name) 方法:当使用不可访问的(私有或受保护的)变量或不存在的变量时,将调用此方法。
PHP
value;
?>
You are trying to get 'value' which is either
inaccessible or non existing member
__set($name, $value) 方法:当试图修改或更改不可访问的变量或不存在的变量时调用此方法。
PHP
value = "Hello";
?>
You are trying to modify 'value' with 'Hello' which is either inaccessible
or non-existing member
__debugInfo() 方法:当以对象为参数调用var_dump()函数时使用此方法。此方法应返回一个数组,其中包含可能对调试有用的所有变量。
PHP
"value");
}
}
$obj = new MagicMethod();
var_dump($obj);
?>
object(MagicMethod)#1 (1) {
["variable"]=>
string(5) "value"
}