php - 魔术方法(__get、__set)在扩展类中不起作用?

标签 php

<分区>

<?php 

abstract class AbstractClass
{
    public function __get($theName)
    {
        return (isset($this->$theName)) ? $this->$theName : NULL;
    }

    public function __set($theName, $theValue)
    {
        if (false === property_exists(get_class(), $theName)) {
            throw new Exception(get_class()." does not have '".$theName."' property.");
        } else {
            $this->$theName = $theValue;
        }
    }
}

class ConcreteClass extends AbstractClass
{
        private $x;
        private $y;

        public function __construct($theX, $theY)
        {
            $this->x = $theX;
            $this->y = $theY;
        }
}

$concreteClass = new ConcreteClass(10, 20);

var_dump( $concreteClass->x );

有什么方法可以完成这项工作,还是我必须将这些魔术方法添加到扩展类中?

最佳答案

这会起作用:

public function __get($theName)
{
    if(property_exists($this, $theName)) {
        $reflection = new ReflectionProperty($this, $theName);
        $reflection->setAccessible($theName);
        return $reflection->getValue($this);
    }
}

IMO,您不应该使用 __get__set 来替代 getter 和 setter。由于它们在尝试访问不可访问的属性时被触发,因此它们与错误处理更相关。而且它们也比常规的 getter 或 setter 慢得多。

关于php - 魔术方法(__get、__set)在扩展类中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5421295/

相关文章:

javascript - 将 ajax 请求更改为不同的 php 文件漏洞,潜在漏洞利用说明

php - 警告:mysqli::__construct(): (HY000/1045): ProxySQL 错误:第 12 行用户 'root' @'2a02:4780:bad:f00d::18'(使用密码:NO)的访问被拒绝

php - Laravel 5.5 - 排队事件监听器的 Horizo​​n 自定义作业标签

php - SQL时间段查询

php - 显示 json 数据以查看为字符串或数组

php - 计算两个月数据的差异

php - 如何将媒体选择器添加到 WordPress 中的 add_settings_field?

php - $results 返回多个结果,但只有最后一个在 mysql_query 上更新。需要全部更新

php - fatal error : Call to a member function bind_param() PHP MySQL Prepared Statements

php - 如何单独交叉引用数据库表?