PHP魔术方法__get()

2018-09-16 11:00 By "Powerless" 2650 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

评 论

Others Discussion

  • 分布式服务限流
    Posted on 2020-02-07 18:57
  • 有状态服务VS无状态服务
    Posted on 2020-02-07 18:18
  • 企业级PAAS云平台几个关键问题和挑战
    Posted on 2019-06-12 18:33
  • MySQL 单库后期分库策略
    Posted on 2019-08-19 14:31
  • 关于HTTPS的五大误区
    Posted on 2020-02-02 01:10
  • Redis七大经典问题
    Posted on 2021-05-27 11:14
  • PHP扩展GD安装
    Posted on 2018-10-29 18:29
  • PHP实现精确发布时间
    Posted on 2018-12-06 21:00