2017-06-11 35 views
-2

嗨,我有這個錯誤的示例代碼。

例外:使用$這個時候不是在對象上下文

<?php 

Class A { 
public function test($str) 
{ 
    return trim($str); 
} 
} 


Class B { 

protected $trim; 
public function __construct(A $trim){ 
    $this->trim = $trim; 
} 

public static function trim_str($str) 
{ 
    return $this->trim->test($str); 
} 
} 

//implementation 
B::trim_str(" TRIM ME "); 

?> 

任何人都可以賜教。 謝謝

+3

'$ this'指給定對象的一個​​實例。但是靜態並沒有真正與實例相關,所以你不能在靜態方法中使用'$ this'。 – FirstOne

+0

我如何重構代碼?在靜態方法內實例化類A?這是一個好習慣嗎? –

+0

刪除靜態並嘗試 –

回答

-2

在類中的靜態方法的上下文中不能使用$this,因爲它不屬於發生錯誤的原因的實例。

作爲每PHP手冊:

因爲靜態方法是沒有類的實例可調用,僞變量$這是不可用內部的方法聲明爲靜態的。

請參考PHP手冊文檔的簡要說明(http://php.net/manual/en/language.oop5.static.php

0
Class B 
{ 

    protected $trim; 

    public function __construct(A $trim) 
    { 
     $this->trim = $trim; 
    } 

    public static function trim_str($str) 
    { 
     return $this->trim->test($str); //You Cannot access $this here 
    } 
} 

可能的解決方案

變化$修剪變量靜態

Class B 
{ 
    protected static $trim; 

    public function __construct(A $trim) 
    { 
     static::$trim = $trim; 
    } 

    public static function trim_str($str) 
    { 
     return static::$trim->test($str); 
    } 
} 
+0

我會試試這個。感謝您的輸入.. –

相關問題