2010-09-25 63 views
0

我有以下的PHP对象,但我努力从对象中获取数组项。在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)) 

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

最好的办法是抓住数组?

回答

10

如果你可以编辑类,要么改变你所关心的财产,以公共或为它编写一个getter:

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

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

class YourClass extends ThatClass { 

    public function getItems { 
     //parent $items really 
     return $this->items ; 
    } 

} 

然后,你需要创建YourClass而不是ThatClass的实例,并从中获得项目阵列。

类似地,你想要的任何其他受保护的属性。

+0

看着编辑过的清理过的代码显示,您可能正在寻找'$ this-> progress'而不是'items',但是同样的方法也适用。 – Fanis 2010-09-26 08:33:54

3

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

对象类里面,你应该写这样的函数:

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

最初的意图是明显的,以保持该属性的内部和外部修饰安全,所以我会用这种方法,而不是为例如,将protected $feed_nid声明更改为public