首页 > 解决方案 > 混合 __get 和 __set 调用的 PHP 问题

问题描述

混合使用 __get 和 __set 方法时出现问题

class TestClass {}

$obj = new TestClass();
var_dump($obj->test); //throw notice as expected
$obj->invalidprop['key'] = 'test';

var_dump($obj->invalidprop);
//=> array('key' => 'test')

通过使用具有值的数组填充动态属性,本机行为可以完美地工作,并且警告/通知为零。

但是一旦我添加了 __get 和 __set 来添加一些功能,我就无法重现默认行为。

class TestClass {
    public function &__get($prop) {
        if (method_exists($this, 'get' . $prop)) {
             $func = 'get' . $prop;
             return $this->$func();
        }

        //else throw default notice warning
        trigger_error('Undefined property ... ');
    }

    public function __set($prop, $value) {
        $this->$prop = $value;
    }
}

所以我再次运行,它 在访问时$obj->invalidprop['key'] = 'test';触发,同时因为它正在分配一个值。它不仅抛出了我定义的自定义 trigger_error,而且也没有按预期填充数组。__getinvalidprop__set

问题:如何在 __get() 中保留相同的附加功能的同时重现本机行为(带有 0 通知警告)?

标签: php

解决方案


这样它工作正常:

<?php

class TestClass {

    public function &__get($prop) {
        echo "Get Prop: $prop\n";

        if (method_exists($this, 'get' . $prop)) {
             $func = 'get' . $prop;
             return $this->$func();
        }

        //else throw default notice warning
        trigger_error('Undefined property ... ');
    }

    public function __set($prop, $value) {

        echo "Set Prop: $prop\n";
        $this->$prop = $value;
    }
}

$obj = new TestClass;

$obj->invalidprop = ['key' => 'test'];
var_dump($obj->invalidprop);

推荐阅读