简体   繁体   中英

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;

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;

Simply this does not work -- you can not add class methods dynamically in PHP, period. This was discussed at places like define a closure as method from class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM