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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵