我们可以使用__get()方法来解决这个问题。它能在对象外部取得对象的私有方法。
示例如下:
class Person
{
private $name;
private $age;
function __construct($name="", $age=1)
{
$this->name = $name;
$this->age = $age;
}
public function __get($propertyName)
{
if ($propertyName == "age") {
if ($this->age > 30) {
return $this->age - 10;
} else {
return $this->$propertyName;
}
} else {
return $this->$propertyName;
}
}
}
$Person = new Person("John", 60); // 用Person类初始化对象,并通过构造方法给属性赋初始值
echo "Name:" . $Person->name . "
"; // 访问私有属性时, __get() 方法会自动被调用,这样就能间接取得属性值
echo "Age:" . $Person->age . "
"; // __get() 方法自动被调用,并返回不同的值
输出结果如下:
Name: John
Age: 50