Fab*_*lio 7 php laravel laravel-4
我正在尝试使用变量$ 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;
}
Run Code Online (Sandbox Code Playgroud)
Roy*_* Bg 17
$this当您使用静态方法时,无法使用.静态方法不知道对象状态.您只能使用静态属性和对象self::.如果你想使用对象本身,你需要觉得自己不在课堂上,所以你需要创建一个实例,但是这将无法理解之前在对象中发生的事情.即如果某些方法将属性更改$_x为某个值,则在重新生成对象时,将丢失此值.
但是,在你的情况下,你可以做到
$_this = new self;
$_this->event->create($info);
Run Code Online (Sandbox Code Playgroud)
您也可以将非静态方法称为静态方法,self::method()但在较新版本的PHP中,您将收到此错误,因此最好不要这样做.
关于它的信息,你可以在官方的PHP文档中找到:http://www.php.net/manual/en/language.oop5.static.php
因为静态方法可以在没有创建对象实例的情况下调用,所以伪变量$ this在声明为static的方法中不可用
静态调用非静态方法会生成E_STRICT级别警告.