0

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;
Cœur
  • 37,241
  • 25
  • 195
  • 267
Spechal
  • 2,634
  • 6
  • 32
  • 48

2 Answers2

3

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;
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0

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.

Community
  • 1
  • 1
chx
  • 11,270
  • 7
  • 55
  • 129