我试图用变量$this访问构造函数上的实例;在所有其他方法中,调用$this->event->method()似乎很好,但是在这个方法上它会抛出一个错误。
在对象上下文中不使用$this
我刚刚对这个问题做了研究,我找到的答案都是关于PHP版本的,但我有5.4版。有什么问题吗?
这是我试图调用实例的方法。
// all protected variable $event , $team , $app
function __construct(EventTeamInterface $event,TeamInterface $team) {
$this->event = $event;
$this->team = $team;
$this->app = app();
}
/**
* @param $infos array() |
* @return array() | ['status'] | ['msg'] | ['id']
*/
public static function createEvent($infos = array()){
$create_event = $this->event->create($infos);
if ($create_event) {
$result['status'] = "success";
$result['id'] = $create_event->id;
} else {
$result['status'] = "error";
$result['msg'] = $create_event->errors();
}
return $result;
}发布于 2014-01-25 11:16:26
在静态方法中不能使用$this。静态方法不知道对象状态。您只能使用self::引用静态属性和对象。如果您想使用对象本身,您需要感觉自己脱离了类,所以您需要创建一个实例,但这将无法理解对象中以前发生的事情。也就是说,如果某个方法将属性$_x更改为某个值,则当您重新实例该对象时,您将丢失该值。
但是,在您的情况下,您可以
$_this = new self;
$_this->event->create($info);您也可以将非静态方法调用为静态self::method(),但是在较新版本的PHP中,会出现错误,所以最好不要这样做。
有关它的信息,您可以在正式的php文档中找到:http://www.php.net/manual/en/language.oop5.static.php。
由于静态方法在没有创建对象实例的情况下是可调用的,因此在声明为静态的方法中,伪变量$this不可用。
静态调用非静态方法将生成E_STRICT级别警告。
https://stackoverflow.com/questions/21349732
复制相似问题