【问题标题】:array requested by name in variable doesn't works变量中名称请求的数组不起作用
【发布时间】:2015-07-19 17:49:38
【问题描述】:

我在对象中有数组,在变量中有他的名字。当我请求 $object->$propertyWithArrayName 时,它​​的返回数组很好,但是当我想从该数组的索引处获取值时它不起作用。

代码:

class Foo {
    public $bar;

    public function __construct() {
        $this->bar = array("A" => "a", "B" => "b");
    }
}

$test = new Foo();
$propertyName = "bar";
var_dump($test->$propertyName); // ok
var_dump($test->$propertyName["A"]); // doesn't work

第二个 var_dump 引发 Warning: Illegal string offset 'A'Notice: Undefined property: Foo::$b

为什么它不起作用?

【问题讨论】:

    标签: php arrays variables undefined


    【解决方案1】:

    $propertyName 是字符串而不是数组,因此要使用字符串作为名称来获取数组,您需要使用花括号 { } 消除歧义:

    var_dump(
        $test->{$propertyName}["A"]
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2019-08-17
      • 1970-01-01
      • 2012-05-09
      • 2019-03-23
      • 2017-03-19
      • 1970-01-01
      相关资源
      最近更新 更多