变量中名称请求的数组不起作用
array requested by name in variable doesn't works
我在对象中有数组,在变量中有他的名字。当我请求 $object->$propertyWithArrayName 时,它的 return 数组很好,但是当我想从这个数组的索引处获取值时,它不起作用。
代码:
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
。
为什么不起作用?
$propertyName
是字符串而不是数组,因此要使用字符串作为名称获取数组,您需要使用花括号 { }
:
来消除歧义
var_dump(
$test->{$propertyName}["A"]
);
我在对象中有数组,在变量中有他的名字。当我请求 $object->$propertyWithArrayName 时,它的 return 数组很好,但是当我想从这个数组的索引处获取值时,它不起作用。
代码:
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
。
为什么不起作用?
$propertyName
是字符串而不是数组,因此要使用字符串作为名称获取数组,您需要使用花括号 { }
:
var_dump(
$test->{$propertyName}["A"]
);