Call an Object inside of a function

前端 未结 1 1491
我在风中等你
我在风中等你 2020-12-28 23:37

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         


        
相关标签:
1条回答
  • 2020-12-29 00:13

    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!

    0 讨论(0)
提交回复
热议问题