Instantiating objects dynamically

Asked

Viewed 257 times

3

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

Fatal error: Call to a Member Function geturl() on a non-object in ... on line 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 repeat loops and the condition.

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

When I instantiate the object outside the loop the code works as expected. I’m using the access modifiers the wrong way?

Related but it didn’t help.

  • 2

    Its object $thumb is only created if you enter if you do not enter the error that is in the question.

  • The interesting thing is that this does not happen in PHP 7.

  • 1

    Your method is protected, it would need to be public, no?

  • I assume not @bfavaretto. $sizeName is a class that extends to that which possesses the method. @rray is right, as the code snippet runs hundreds of times did not realize that in some cases it did not enter the if.

  • Actually I had to be public same, huh? Protected would only be accessible from within the class (or derivatives).

  • Exactly @bfavaretto, $thumb is derived from the class having the method getUrl().

  • David, but you are calling from outside the class itself (from an instance). In that case, it needs to be public. Isn’t it, @rray? Whether or not to enter if.

Show 3 more comments

1 answer

2


The error happens because the condition of the if is not met in all cases and so $thumb does not always have an object and method getUrl() does not exist. To solve the problem just 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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.