【问题标题】:PHP method to get values dynamically from an array object property从数组对象属性动态获取值的 PHP 方法
【发布时间】:2014-08-26 19:40:12
【问题描述】:

在这个类中,是否可以从数组中动态获取一个值?

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

【问题讨论】:

  • 如果您仍然想要一个公共访问器方法,不妨将$array_data 公开。
  • @Supericy,在我的应用程序中,我需要通过方法访问这些数据
  • PHP dynamic array index name 的可能重复项

标签: php arrays object properties


【解决方案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'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多