
在PHP中,魔术方法是一种特殊的函数,用于在对象创建、销毁、赋值等特定情况下自动调用。以下是一些常见的PHP魔术口诀及其使用实例,并通过表格形式展示。
1. 构造函数 __construct()
构造函数在对象创建时自动调用,用于初始化对象属性。
| 方法 | 说明 | 实例 |
|---|
| __construct() | 构造函数 | ```php |
class Person { public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
$person = new Person('张三', 20);
echo $person->name . ',' . $person->age;
``` |
2. 析构函数 __destruct()
析构函数在对象销毁时自动调用,用于清理资源。
| 方法 | 说明 | 实例 |
|---|
| __destruct() | 析构函数 | ```php |
class Person { public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function __destruct() {
echo '对象销毁,资源清理';
}
}
$person = new Person('张三', 20);
``` |
3. 赋值运算符 __set()
当尝试给对象属性赋值时,会调用__set()方法。
| 方法 | 说明 | 实例 |
|---|
| __set($name,$value) | 赋值运算符 | ```php |
class Person { private $name;
public function __set($name, $value) {
$this->$name = $value;
}
public function getName() {
return $this->name;
}
}
$person = new Person();
$person->__set('name', '张三');
echo $person->getName();
``` |
4. 取值运算符 __get()
当尝试获取对象属性时,会调用__get()方法。
| 方法 | 说明 | 实例 |
|---|
| __get($name) | 取值运算符 | ```php |
class Person { private $name;
public function __get($name) {
return $this->$name;
}
}
$person = new Person();
$person->name = '张三';
echo $person->name;
``` |
5. 索引运算符 __isset()
当尝试检查对象属性是否存在时,会调用__isset()方法。
| 方法 | 说明 | 实例 |
|---|
| __isset($name) | 索引运算符 | ```php |
class Person { private $name;
public function __isset($name) {
return isset($this->$name);
}
}
$person = new Person();
$person->name = '张三';
var_dump(isset($person->name)); // 输出:bool(true)
``` |
6. 索引赋值运算符 __set()
当尝试给对象属性赋值时,会调用__set()方法。
| 方法 | 说明 | 实例 |
|---|
| __set($name,$value) | 索引赋值运算符 | ```php |
class Person { private $name;
public function __set($name, $value) {
$this->$name = $value;
}
public function __isset($name) {
return isset($this->$name);
}
}
$person = new Person();
$person->name = '张三';
var_dump(isset($person->name)); // 输出:bool(true)
``` |
7. 索引访问运算符 __get()
当尝试获取对象属性时,会调用__get()方法。
| 方法 | 说明 | 实例 |
|---|
| __get($name) | 索引访问运算符 | ```php |
class Person { private $name;
public function __get($name) {
return $this->$name;
}
}
$person = new Person();
$person->name = '张三';
echo $person->name;
``` |
8. 索引删除运算符 __unset()
当尝试删除对象属性时,会调用__unset()方法。
| 方法 | 说明 | 实例 |
|---|
| __unset($name) | 索引删除运算符 | ```php |
class Person { private $name;
public function __unset($name) {
unset($this->$name);
}
}
$person = new Person();
$person->name = '张三';
unset($person->name);
echo $person->name; // 输出:空字符串
``` |
通过以上表格,我们可以清晰地了解PHP中的魔术方法及其应用。希望这些实例能帮助您更好地理解PHP魔术口诀。