2017-05-15 29 views
2

我正在創建一個PHP類,它越來越輕微地失控。如何在PHP中使大型多維變量變得更短?

下面是一個例子:

unset($this->file[$key]->inspect->formats); 
unset($this->file[$key]->inspect->tags); 
unset($this->file[$key]->inspect->chapters); 
unset($this->file[$key]->inspect->annotations); 
unset($this->file[$key]->inspect->automatic_captions); 
unset($this->file[$key]->inspect->subtitles); 

$this->file[$key]->inspect->name = trim($this->file[$key]->inspect->name); 
$this->file[$key]->inspect->artist = trim($this->file[$key]->inspect->artist); 

而是爲每一個變量我想用文字$this->file[$key]->inspect的是有辦法,我可以設置一個變量e.g $inspect採取這個地方?

因此,當我寫$inspect->subtitles它會知道我真正的意思,並影響主要$this->file[$key]->inspect->subtitles

+0

'$檢查= $此 - > file [$ key] - > inspect;' – hassan

+0

@hassan「影響主$ this->文件[$ key] - > inspect->字幕?」如果我按照你的建議去做,那麼運行'$ inspect-> subtitles ='test''它只會影響這個新的對象。當試圖將內存使用量降到最低時,它也沒有什麼幫助 –

+0

$ inspect =&$ this-> file [$ key] - > inspect; – MacBooc

回答

2
$inspect = &$this->file[$key]->inspect; 

聲明這一點。現在,您可以將您的數據是這樣

$inspect->formats = 'format'; 
$inspect->subs = 'subs'; 
// ... 

添加&您會影響變量,不僅這個變量

副本這裏有關於引用的解釋http://php.net/manual/en/language.references.whatare.php

0

您可以使用的一種方法是複製Laravel的object_get()輔助方法,該方法將根據dot表示法獲取元素。

/** 
* Get an item from an object using "dot" notation. 
* 
* @param object $object 
* @param string $key 
* @param mixed $default 
* @return mixed 
*/ 
function object_get($object, $key, $default = null) 
{ 
    if (is_null($key) || trim($key) == '') return $object; 

    foreach (explode('.', $key) as $segment) 
    { 
     if (! is_object($object) || ! isset($object->{$segment})) 
     { 
      return value($default); 
     } 

     $object = $object->{$segment}; 
    } 

    return $object; 
} 


$ob = new StdClass(); 

$ob->property->name->value = 'Lol'; 

echo object_get($ob, 'property.name.value'); 

不幸的會是一些額外的實現,如果$object->property就像在你的榜樣陣列。