tags:

views:

297

answers:

1

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

+15  A: 

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!

Peter Bailey
Works great. Thank you!
Tim