Call an Object inside of a function

12,777

This is not an OOP issue, it's a scope issue. $obj isn't visible inside the function go(). You either need to pass it in as a parameter, or bring it into the function's scope with the global keyword (not recommended)

Recommended way

$obj = new OBJ();

go('http://www.mysite.com/hello', $obj);

function go( $url, $object )
{
    $array = $object->grabArray($url);
    echo $array['hits'];
}

Not Recommended way

$obj = new OBJ();

go('http://www.mysite.com/hello');

function go( $url )
{
    global $obj;
    $array = $object->grabArray($url);
    echo $array['hits'];
}

There's another solution which is similar to the OOP concept of composition - you would make the go() function responsible for creating an instance of OBJ.

go('http://www.mysite.com/hello');

function go( $url )
{
    $obj = new OBJ();
    $array = $obj->grabArray($url);
    echo $array['hits'];
}

This is probably not ideal, though, since you'd create a brand new OBJ instance every time you executed go(). You could fix this by "caching" the instance of OBJ inside go() with a static variable

function go( $url )
{
    static $obj;
    if ( is_null( $obj ) )
    {
        $obj = new OBJ();
    }
    $array = $obj->grabArray($url);
    echo $array['hits'];
}

But this composition-like approach is really only useful if you don't use your instance of OBJ anywhere else besides inside the go() function - if you do use it elsewhere, then the parameter approach is the best choice.

It's all about picking the right solution for the task at hand!

Share:
12,777
Tim
Author by

Tim

VP of Product at http://www.ombud.com Likes Product strategy Writing code Designing things Brewing beer Eating BBQ

Updated on June 08, 2022

Comments

  • Tim
    Tim almost 2 years

    So I'm not to OOP in PHP.

    Here is my issue I have a object that I can call a function from and it provides back an arrary. So here is the code.

    $obj = new OBJ();
    
    function go($url){
        $array = $obj->grabArray($url);
        echo $array['hits'];
    }
    
    go('http://www.mysite.com/hello');
    

    This gives me the error

    Fatal error: Call to a member function grabArray() on a non-object