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

标签 php arrays class warnings

我有这个代码:

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'

关于php - "Illegal string offset"对象属性数组警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28018815/

相关文章:

php - 使用 PHP 的 DateTime 警告

php - 我无法升级 WordPress

c - 尝试将输入存储在具有意外行为的结构类型数组中

python - 在类中获取变量?

Java 在两个类之间传递值

php - MYSQL Order By 2 rows depending on 2 other rows IDS

php - 循环数组没有给出所需的结果

c# - 如何计算值在同一数组中重复出现的次数?

java - 未找到 int 数组中的元素(虽然应该找到)

java - 在 java 中,String 是一个类,那么它是如何限制大小分配的