PHP魔术方法__get()

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

  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • BASE原则
    Posted on 2020-12-17 16:42
  • 一些常见的基础概念
    Posted on 2018-11-28 19:10
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00
  • PHP扩展安装
    Posted on 2019-06-24 11:28
  • 程序员年中考试题-段子版
    Posted on 2021-06-23 15:57