"Illegal string offset" 对象 属性 数组的警告?

"Illegal string offset" warning for object property array?

我有这个代码:

class Foo {
    public $bar = array();
}

$foo = new Foo();

$foo -> bar['count'] = 100;
echo $foo -> bar['count']; // 100

$prop = 'bar';
echo $foo -> $prop['count']; // Warning: Illegal string offset 'count'

这给了我这个错误:

Warning: Illegal string offset 'count' in ...

为什么?以及如何让它发挥作用?

===================

我想要这个的原因是:

class Foo {
    private $data1 = array();
    private $data2 = array();

    public function loadData1(array $data) {
        return $this -> loadDataInProperty($data, 'data1');
    }

    public function loadData2(array $data) {
        return $this -> loadDataInProperty($data, 'data2');
    }

    private function loadDataInProperty(array $data, $prop) {
        // Filtering, etc.
        foreach ($data as $key => $value) {
            // Keys comparison, etc.
            $this -> $prop[$key] = $value;
        }
    }
}

基本上,我想将一些数据加载到对象的一个​​属性(数组)中。有很多不同的数据集。有没有更好/更酷的方法来实现这个目标?

试试这个:

<?php
class Foo {
    public $bar = array();
}

$foo = new Foo();

$foo -> bar['count'] = 100;
echo $foo -> bar['count']; // 100
$prop = 'bar';
echo $foo -> {$prop}['count']; // Warning: Illegal string offset 'count'