van_folmert
van_folmert

Reputation: 4517

How to call anonymous function (Closure) from inline object?

I need to quickly mock an object, so that when in template appears:

$that->user->isAdmin()

it will return true.

I tried to cast an array with anonymous function into object:

$that = (object) ( (array(
    'user'      =>
        (object) (array(
            'isAdmin' => function() {
                return true;
            }
(...)

but var_dump($that->user) returns an empty(?) Closure:

object(stdClass)#3 (1) {
  ["isAdmin"]=>
  object(Closure)#2 (1) {
    ["this"]=>
    object(View)#1 (0) {
    }
  }
}

and calling it directly by $that->user->isAdmin() returns Call to undefined method stdClass::isAdmin().

How can I rewrite $that in order to be able to call $that->user->isAdmin()?

Can be done in a dirty/hacky way, since it's only for a mocking purpose.

Upvotes: 0

Views: 64

Answers (1)

Federkun
Federkun

Reputation: 36964

$that->user->isAdmin is a propriety of the $that->user object, that's also a Closure. If you try to call it with $that->user->isAdmin(), you are trying to call the method isAdmin instead.

From php7 you can call it with

$bool = ($that->user->isAdmin)();

Otherwhise you can put $that->user->isAdmin in a variable and call it, or use call_user_func instead.

EDIT

If you want a method isAdmin:

$that = (object) ( (array(
    'user' => new class {
        public function isAdmin() {
            return true;
        }
    })
));

$bool = $that->user->isAdmin();

Upvotes: 1

Related Questions