douzhuan0309 2015-12-07 13:39
浏览 13
已采纳

Zend Framework 2:致命错误 - 在不在对象上下文中时使用$ this

Here's my code, in Module.php:

public function onBootstrap(MvcEvent $mvcEvent)
{
    $sm = $mvcEvent->getApplication()->getServiceManager();

    $myServiceEM = $sm->get('MyModule\Service\MyService')->getEventManager();
    $myServiceEM->attach(
        'myevent.post', ['MyModule\Controller\MyController', 'myFunction']
    );
}

And here's myFunction() in MyModule\Controller\MyController:

public function myFunction(Event $e)
{
    $myTestFunc = $this->getMyTestFunc();
}

But when I call getMyTestFunc() function this error appears:

Fatal error: Uncaught Error: Using $this when not in object context

  • 写回答

1条回答 默认 最新

  • dongyan6503 2015-12-07 13:57
    关注

    ['MyModule\Controller\MyController', 'myFunction'] is a callable for a static method; therefore you can't use $this there.
    Consider

    <?php
    class Foo {
        protected $prop = 'value';
        public function memberMethod() {
            return $this->prop;
        }
    
        public static function staticMethod() {
            return 'static';
        }
    }
    echo Foo::staticMethod(), "
    ";
    // Foo::memberMethod(); // results in Fatal error: Using $this when not in object context
    
    bar( 'myevent.post', array('Foo', 'staticMethod') );
    // bar( 'myevent.post', array('Foo', 'memberMethod') ); // // again: Fatal error: Using $this when not in object context
    
    // to call memberFunction() you need an instance to call the method on
    $foo = new Foo;
    echo $foo->memberMethod(), "
    ";
    bar( 'myevent.post', array($foo, 'memberMethod') );
    
    
    function bar( $something, $callback ) {
        // invoking the callback immediately
        // ZendFramework will store the callback and invoke it when the specified event occurs
        echo $callback(), "
    ";
    }
    

    Now replace function bar() by Zend\EventManager::attach() and class Foo by MyModule\Controller\MyController and you're "at" the problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog