PHP方法从阵列对象属性动态地获取值(PHP method to get values dynami

2019-10-30 11:48发布

在这一类,是有可能动态获取从数组的值?

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']"));

Answer 1:

这里有一个简单的解决方案。 而不是通过在索引中的字符串,则在数组中传递。

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;
}

然后,而不是字符串,你会传递一个数组:

$MyClass->getIndexValue(['first', 'a'])


文章来源: PHP method to get values dynamically from an array object property