[英]Accessing Values From Object property that is an array
How can I access values from an object property that is an array? 如何从数组的对象属性访问值?
For example: 例如:
$myObject = new MyClass;
$myObject->myproperty = array(1 => 'English', 2 => 'French', 3 => 'German');
How can I get individual property values using the array keys from $myObject->mypropery
? 如何使用
$myObject->mypropery
的数组键获取单个属性值? Using $myObject->myproperty[3]
does not work. 使用
$myObject->myproperty[3]
不起作用。
EDIT: Using $myObject->myproperty[3]
does in fact work. 编辑:使用
$myObject->myproperty[3]
确实有效。 Where I find a problem is when doing it like this: 我发现问题的地方是这样的:
$myproperty = 'myproperty';
echo $myObject->$myproperty[3]
// result : 'r'
Yet if I do a var_dump on $myObject->$myproperty
I see my array. 但是,如果我在
$myObject->$myproperty
上执行var_dump, $myObject->$myproperty
看到数组。
try this: 尝试这个:
$myObject->myproperty[3]
instead of this: 代替这个:
$myObject->$myproperty[3]
$tmp = $myObject->$myproperty;
echo $tmp[1];
//or
echo $myObject->{$myproperty}[1];
To access your myproperty
array values try this: 要访问您的
myproperty
数组值,请尝试以下操作:
$myObject->{$myproperty}[3]
Instead of: 代替:
$myObject->$myproperty[3]
These are referred to as Variables Variable, for more information visit: http://php.net/manual/en/language.variables.variable.php 这些称为变量变量,有关更多信息,请访问: http : //php.net/manual/en/language.variables.variable.php
The reason your echo
result was r
is because your $mypropery
value is mypropery
and you executed this echo $myObject->$myproperty[3]
which translate to saying you want the third character array keys value. echo
结果为r
的原因是因为您的$mypropery
值是mypropery
并且执行了此echo $myObject->$myproperty[3]
,这意味着您需要第三个字符数组键值。 Since arrays are zero based this means you will get the character r
as a result. 由于数组是从零开始的,这意味着您将得到字符
r
。 Hope this clears up why your result was r
. 希望这可以弄清为什么您的结果是
r
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.