Chaosjosh
Chaosjosh

Reputation: 137

Calling Class property using variables in Zend

I am creating partials where an items property names are passed from an array to access the values of those properties but I receive an error saying Undefined property of Namespace\Entity::$variable when defining $property->{$variable}. How would I go about getting this to work?

Here is an example of the code:

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}));
        }
    }
}

Upvotes: 0

Views: 97

Answers (1)

Dolly Aswin
Dolly Aswin

Reputation: 2794

If you accessing the property like this $item->thumb{$thumb_size}, it mean the $item has property thumb with array keys as the value. Here is the ilustration

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

But, if you imagine use this way $item->thumb{$thumb_size} to access property of $item, you cannot concatenate the property name with variable. If you want to concatenate the variable, please do it first, and save to a variable. Then access the property using the variable name like this

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

Upvotes: 0

Related Questions