PHP魔术方法__get()

2018-09-16 11:00 By "Powerless" 2749 0 1

我们可以使用__get()方法来解决这个问题。它能在对象外部取得对象的私有方法。

示例如下:

<?php
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 . "<br>";   // 访问私有属性时, __get() 方法会自动被调用,这样就能间接取得属性值
echo "Age:" . $Person->age . "<br>";    // __get() 方法自动被调用,并返回不同的值

输出结果如下:

Name: John
Age: 50

评 论

View in WeChat

Others Discussion

  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • 快速了解Kafka
    Posted on 2021-03-25 14:20
  • 通过信鸽来解释HTTPS
    Posted on 2018-10-22 13:56
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00