【问题标题】:Access array in PHP objectPHP对象中的访问数组
【发布时间】:2010-09-25 23:01:47
【问题描述】:

我有以下 PHP 对象,但我正在努力将数组项从对象中取出。

exampleBatch Object (
[file_path:protected] => 
[title:protected] => 
[description:protected] => 
[link:protected] => 
[items:protected] => Array ( ) 
[raw:protected] => data/example 
[feed_nid:protected] => 
Array ( 
    [0] => Array ( [path] => data/example/example/ [filename] => file.csv ) 
    [1] => Array ( [path] => data/example/example/ [filename] => file.csv ) 
    [2] => Array ( [path] => dexampleata/example// [filename] => file.csv ) ) 
[current_item:protected] => 
[created] => 0 
[updated] => 0 
[total:protected] => Array ( ) 
[progress:protected] => Array ( [fetching] => 1 [parsing] => 1 [processing] => 1 ) )

我需要访问包含三个键的数组,它是一些后期处理的数据。

获取数组的最佳方法是什么?

【问题讨论】:

    标签: php arrays object


    【解决方案1】:

    如果您可以编辑该类,请将您关心的属性更改为 public 或为其编写一个 getter:

    function getItems() {
        return $this->items ;
    }
    

    否则,如果你不能编辑类本身,你可以扩展它,因为你想要的属性是受保护的,这意味着子类可以访问它们:

    class YourClass extends ThatClass {
    
        public function getItems {
            //parent $items really
            return $this->items ;
        }
    
    }
    

    然后您需要创建 YourClass 的实例而不是 ThatClass 并从中获取 items 数组。

    同样适用于您想要的任何其他受保护属性。

    【讨论】:

    • 查看编辑后的清理代码显示,您可能正在寻找$this->progress 而不是items,但同样的方法也适用。
    【解决方案2】:

    对象的feed_nid 属性受到保护,因此无法从对象外部访问。

    在对象类中,你应该写一个这样的函数:

    function getFeedNid()
    {
        return $this->feed_nid;
    }
    

    最初的意图显然是保持该属性在内部并且不受外部修改,因此我将使用此方法而不是例如将protected $feed_nid 声明更改为public

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 2014-10-17
      • 2012-02-03
      • 1970-01-01
      相关资源
      最近更新 更多