PHP 魔术方法
时间:2018-11-15 15:13:28 来源:igfitidea点击:
在本教程中,我们将介绍一些重要的PHP魔术方法,您可以使用它们来处理不存在的成员和方法。
PHP的__get()和__set()方法
PHP提供了一对魔术方法来处理不存在的或私有属性的访问:
- 每次当您试图访问对象的不存在或私有的属性时,都会调用
__get()方法。 - 每次当您试图修改对象的不存在或私有的属性时,都会调用
__set()方法。
让我们看下面的例子:
<?php
class Person{
private $firstName;
public function __get($propertyName){
echo "试图访问不存在的属性: $propertyName ";
}
public function __set($propertyNane, $propertyValue){
echo "试图修改不存在的属性: $propertyNane ";
}
}
$p = new Person();
$p->firstName = 'alice';
echo $p->firstName;
$p->lastName = 'itroad';
echo $p->lastName;
使用__get()和__set()可以把类的单独属性放到一个关联数组中,请看下面的示例:
<?php
class Person{
private $properties;
public function __get($propertyName){
if(array_key_exists($propertyName, $properties)){
return $this->properties[$propertyName];
}
}
public function __set($propertyNane, $propertyValue){
$this->properties[$propertyNane] = $propertyValue;
}
}
$p = new Person();
$p->lastName = 'alice';
$p->firstName = 'itroad';
var_dump($p);
PHP __call() 方法
与_get()和_set()方法类似,当调用类中不存在的方法时,会自动调用_call()魔术方法。
下面的示例演示了一个简单的string类,它支持三种方法:strlen()、strtoupper()和strtolower()。
<?php
class CString{
private $str = '';
private $APIs = array('strlen','strtoupper','strtolower');
public function __construct($str){
$this->str = $str;
}
public function __call($method,$args){
if(in_array($method, $this->APIs)){
array_unshift($args, $this->str);
return call_user_func_array($method, $args);
}else{
die('错误:调用不支持的方法: ' . $method);
}
}
}
$str = new CString('这是一字符串对象');
echo $str->strlen() . '';
echo $str->strtoupper() . '';
echo $str->strtolower() . '';
echo $str->len(); // 错误:调用不支持的方法: len
PHP使用双下划线(__)作为类中魔术方法的前缀,因此建议您定义方法名时不要以双下划线(__)开头。
注意,构造函数和析构函数方法(__construct() 和 __destruct() )也是魔术方法。

