1、什么是重载
1)PHP所提供的"重载"(overloading)是指动态地"创建"类属性和方法,我们是通过魔术方法来实现的。
2)当调用当前环境下未定义或不可见的类属性或方法时,重载方法会被调用。(屏蔽错误)
3)所有的重载方法都必须被声明为 public。
4)属性重载只能在对象中进行。在静态方式中,这些魔术方法将不会被调用。所以这些方法都不能被 声明为 static。
5)这些魔术方法的参数都不能通过引用传递。
2、属性重载
1)__get()魔术方法
描述:读取不可访问属性的值时,__get() 会被调用。
语法:public mixed __get ( string $name )

<?php
class Db
{
protected $salary;
private $age;
public $name;
public function __construct($salary, $age, $name)
{
$this->salary = $salary;
$this->age = $age;
$this->name = $name;
}
// 查看无权限属性的方法
public function __get($value)
{
if($value==='age'){
return ($this->name==='神仙不爱')?$this->age:'无权查看';
}
return $this->$value;
}
}
$db = new Db(3000,26,'神仙不爱');
ECHO $db->salary;点击 "运行实例" 按钮查看在线实例
2)__set()魔术方法
描述:在给不可访问属性赋值时,__set() 会被调用。
语法:public void __set ( string $name , mixed $value )

3)__isset()魔术方法
描述:当对不可访问属性调用 isset() 或 empty() 时,__isset()会被调用。
语法:public bool __isset ( string $name )

4)__unset()魔术方法
描述:当对不可访问属性调用 unset() 时,__unset()会被调用。
语法:public void __unset ( string $name )

3、方法重载
1)__call()魔术方法
描述:在对象中调用一个不可访问方法时,__call() 会被调用。
语法:public mixed __call ( string $name , array $arguments )

2)__callStatic()魔术方法
描述:用静态方式中调用一个不可访问方法时,__callStatic() 会被调用。
语法:public static mixed __callStatic ( string $name , array $arguments )

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号