[英]PHP method to get values dynamically from an array object property
In this class, is it possible to get dynamically a value from the array? 在此类中,可以从数组中动态获取值吗?
class MyClass {
private $array_data;
function __construct() {
$this->array_data['first']['a'] = '1';
$this->array_data['second']['b'] = '2';
$this->array_data['third']['c'] = '3';
}
public function getIndexValue($index){
return $this->{'array_data' . $index};
}
}
$MyClass = new MyClass();
// Prints NULL, but i expect '1'
var_dump($MyClass->getIndexValue("['first']['a']"));
Here's a simple solution. 这是一个简单的解决方案。 Rather than passing in a string for the indexes, you pass in an array.
而不是为索引传递字符串,而是传递数组。
public function getIndexValue(array $indexes) {
// count the # of indexes we have
$count = count($indexes);
// local reference to data
$data = $this->array_data;
for ($i = 0; $i < $count; $i++)
{
// enter the array at the current index
$data = $data[$indexes[$i]];
}
return $data;
}
And then rather than a string, you'd pass in an array: 然后,您将传递一个数组,而不是一个字符串:
$MyClass->getIndexValue(['first', 'a'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.