dsfvsdfv23599 2016-11-28 16:03
浏览 45
已采纳

如何从内联对象调用匿名函数(Closure)?

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条回答 默认 最新

  • dskld5423 2016-11-28 16:11
    关注

    $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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C# 调用Bartender打印机打印
  • ¥100 华为ensp只要2-9实验运行结果能做的来加我QQ
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。
  • ¥15 已知隐函数其中一个变量τ的具体值,求另一个变量
  • ¥15 r语言Hurst指数
  • ¥15 Acrn IVSHMEM doorbell问题
  • ¥15 yolov5中的val测试集训练时数量变小问题
  • ¥15 MPLS/VPN实验中MPLS的配置问题