PHP魔术方法__get和[]使值消失

标签 php arrays properties get

我遇到了一个有趣的问题。使用 [] 在同一操作中创建数组属性并为其赋值似乎出错了。

class T
{
    public function __get($property)
    {
        if (!isset($this->{$property}))
        {
            $this->{$property} = array();
        }           

        return $this->{$property};
    }

    public function __set($key, $val)
    {       
        $this->{$key} = $val;
    }

}

$testObj = new T();

$testObj->testArr[] = 1;
$testObj->testArr[] = 2;    
$testObj->testArr[] = 3;

var_dump($testObj->testArr);

输出如下:

array(2) { [0]=> int(2) [1]=> int(3) }

于是1真的像戴帽子的兔子一样神奇地消失在了数组初始化中。如果我在分配之前尝试所有 $testObj->testArr 或者甚至将 1 分配为 $testObj->testArr = array(1); - 它工作得很好。但我想了解情况并有一个通用的解决方案,而不需要先初始化数组。有办法解决这个问题吗?

最佳答案

$testObj->testArr[] = 1;

给你一个通知:

Notice: Indirect modification of overloaded property T::$testArr has no effect in test.php on line 24

确保你有错误报告turned on .

关于PHP魔术方法__get和[]使值消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30196003/

相关文章:

PHP <?=foo() ?> 不工作

php - YouTube 没有显示为推荐人?

javascript - 为什么这个数组不按照对应的JS显示呢?

c# - Expression<Func<TModel,TProperty>> 作为对象初始化的属性?

Java:我可以要求一个子类来定义一个属性值吗?

python - 向现有 Google AppEngine 数据模型/实体添加新属性的问题

php - 有太多的 php 标签

javascript - 增加添加的 <tr> id

java - 在数组中打印 "x"以下的所有数字

php - 将 SQL 数据库中的约束提取到 PHP 中的 JSON