PHP魔术方法__get()

2018-09-16 11:00 By "Powerless" 2751 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 2020-09-17 18:03
  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29