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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看