0

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.

1 Answer 1

1

$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();
Sign up to request clarification or add additional context in comments.

3 Comments

The tricky part is that it has to be called precisely by $that->user->isAdmin(), because it's a mock. I can only change $that object.
then you don't need a closure, you need a method with that name
regarding your edit - is this construct from PHP7 as well? because I get unexpected 'class' (T_CLASS)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.