1

如何从作为数组的对象属性访问值?

例如:

$myObject = new MyClass;

$myObject->myproperty = array(1 => 'English', 2 => 'French', 3 => 'German');

如何使用来自的数组键获取单个属性值$myObject->mypropery?使用$myObject->myproperty[3]不起作用。

编辑:使用$myObject->myproperty[3]确实有效。我发现问题的地方是这样做的:

$myproperty = 'myproperty';

echo $myObject->$myproperty[3]

// result : 'r'

然而,如果我对我做一个 var_dump ,$myObject->$myproperty我会看到我的数组。

4

3 回答 3

1

试试这个:

$myObject->myproperty[3]

而不是这个:

$myObject->$myproperty[3]
于 2012-12-25T00:21:50.177 回答
0
$tmp = $myObject->$myproperty;
echo $tmp[1];
//or
echo $myObject->{$myproperty}[1];
于 2012-12-25T00:27:05.323 回答
0

要访问您的myproperty数组值,请尝试以下操作:

$myObject->{$myproperty}[3]

代替:

$myObject->$myproperty[3]

这些被称为变量变量,更多信息请访问: 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. Since arrays are zero based this means you will get the character r as a result. Hope this clears up why your result was r.

于 2012-12-25T00:27:23.947 回答