2014-01-25 27 views
6

我正在試圖在變量$ this的構造函數上訪問我的實例,在所有其他方法似乎工作很好,當我打電話$this->event->method()但這種方法,把我的錯誤

在不對象上下文使用$此

我只是做了對這個問題的研究我發現的答案都是關於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; 
    } 

回答

15

當您處於靜態方法時,不能使用$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內不可用的方法 聲明爲static


調用非靜態方法靜態根產生E_STRICT級別 警告。

+0

謝謝你的確切和明確的答案! – Fabrizio

+0

從php 5.4.0開始,閉包(匿名函數)現在支持$ this:http://php.net/manual/en/migration54.new-features.php –

相關問題