Instantiate objects dynamically

3

When I create a new object inside the loop, which has the name in $sizeName , and I try to access the getUrl() method I get:

  

Fatal error: Call to a member function getUrl () on a non-object in ...   online 58

foreach ($this->sizeNames as $sizeName => $sizeAlias)
    foreach ($sizeAlias as $alias)
        if ($size === $alias)
            $thumb = new $sizeName($image[0], $sizeAlias);

    return array(URL . $thumb->getUrl(), $image[1], $image[2], $image[3]);

This is the method:

private static $url;
private static $width;
private static $height;

protected function getUrl()
{
    return self::$url . '/' . self::$width . '/' . self::$height;
}

The code enters the loopback and condition.

var_dump($thumb); //retorna object(....

When you instantiate the object outside the loop, the code works as expected. Am I using the access modifiers in the wrong way?

Related but not helped.

    
asked by anonymous 13.09.2016 / 18:42

1 answer

2

The error happens because the condition of if is not met in all cases and therefore $thumb does not always have an object and the getUrl() method does not exist. To solve the problem, simply ensure that $thumb has an object before accessing the method:

foreach ($this->sizeNames as $sizeName => $sizeAlias)
    foreach ($sizeAlias as $alias)
        if ($size === $alias)
            $thumb = new $sizeName($image[0], $sizeAlias);

return (is_object($thumb)) ? array(URL . $thumb->getUrl(), $image[1], $image[2], $image[3]) : $image;
    
13.09.2016 / 20:06