Search code examples
phpaclphp-5.3anonymous-function

PHP Closure on class member after instantiation yields undefined method


I am trying to hack an ACL into a Template without making the Template aware of the ACL object in the class definition. The following code generates an undefined method Template::isAllowed

Why is this? TIA!



        class ACL {
                protected $allowed = array('anything');

                public function isAllowed($what){
                        if(in_array($what, $this->allowed))
                                return true;
                        return false;
                }
        }

        class Template extends stdClass { }

        $Template = new Template;
        $ACL = new ACL;
        $Template->isAllowed = function($what) use($ACL) { return $ACL->isAllowed($what); };

        if($Template->isAllowed('anything'))
                echo 1;
        else
                echo 2;

Solution

  • This:

    $Template->isAllowed('anything')
    

    actually tells PHP to call a method Template::isAllowed(), which obviously doesn't exist as given by your fatal error.

    You cannot treat Template::isAllowed() as if it were a real method by assigning a closure to a property. However you can still call the closure that is assigned to the $Template->isAllowed property (which is an instance of Closure). To do that, you need to either assign the property to a variable then call that:

    $isAllowed = $Template->isAllowed;
    
    if ($isAllowed('anything'))
        echo 1;
    else
        echo 2;
    

    Or use call_user_func():

    if (call_user_func($Template->isAllowed, 'anything'))
        echo 1;
    else
        echo 2;