2017-06-12 29 views
0

我創建的partials中,項目屬性名稱從數組傳遞以訪問這些屬性的值,但在定義$property->{$variable}時收到錯誤Undefined property of Namespace\Entity::$variable。我將如何去做這個工作?在Zend中使用變量調用Class屬性

下面是代碼的一個例子:如果訪問這樣$item->thumb{$thumb_size}屬性

foreach ($items as $item) { 
    $thumb_sizes = []; 
    foreach ($image_sizes as $thumb_size) { 
     if(!empty($item->thumb{$thumb_size})) { 
      array_push($thumb_sizes, preg_replace('/^http:/i','https:',$item->thumb{$thumb_size})); 
     } 
    } 
} 

回答

0

,它指的是具有$item屬性thumb與數組鍵作爲值。這裏是ilustration

class Item 
{ 
    public $thumb = ["100x100" => "value", "75x75" => "value"]; 
} 

但是,如果你想像用這種方式$item->thumb{$thumb_size}訪問的$item財產,你不能連接可變屬性名。 如果要連接變量,請先執行,然後保存到變量中。然後使用這樣的變量名稱訪問該屬性

$thumbSize = "thumb" . $thumb_size; 
if(!empty($item->$thumbSize)) { 
    . 
    . 
    . 
} 
相關問題