[英]Zend Framework 2: Fatal error - using $this when not in object context
Here's my code, in Module.php : 这是我的代码,在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 : 这是MyModule \\ Controller \\ MyController中的
myFunction()
:
public function myFunction(Event $e)
{
$myTestFunc = $this->getMyTestFunc();
}
But when I call getMyTestFunc()
function this error appears: 但是,当我调用
getMyTestFunc()
函数时,会出现此错误:
Fatal error: Uncaught Error: Using $this when not in object context
致命错误:未被捕获的错误:不在对象上下文中时使用$ this
['MyModule\\Controller\\MyController', 'myFunction']
is a callable for a static method ; ['MyModule\\Controller\\MyController', 'myFunction']
是静态方法的可调用项 ; therefore you can't use $this
there. 因此,您不能在此处使用
$this
。
Consider 考虑
<?php
class Foo {
protected $prop = 'value';
public function memberMethod() {
return $this->prop;
}
public static function staticMethod() {
return 'static';
}
}
echo Foo::staticMethod(), "\r\n";
// 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(), "\r\n";
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(), "\r\n";
}
Now replace function bar()
by Zend\\EventManager::attach()
and class Foo
by MyModule\\Controller\\MyController
and you're "at" the problem. 现在,用
Zend\\EventManager::attach()
替换function bar()
,用MyModule\\Controller\\MyController
替换class Foo
,您就“出问题了”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.