2016-11-09 112 views
0

在嘗試了幾次嘗試之後,出於某種原因,當我嘗試將某個對象從我的課程中刪除時,出現錯誤Access to undeclared static propertyPHP |訪問未聲明的靜態屬性

我的類:

final class repo { 
    var $b; 

    /** 
    * @var \Guzzle\Http\Client 
    */ 
    protected $client; 

    function repo($myvar) 
    { 
     static::$b = $myvar; 
     $this->client = $b; 
    } 
} 

我製作的對象:

$myobj = new repo("test"); 
+3

'$ b'不是一個固定的規則。 '$ this-> b = $ myvar'或'public static $ b;' – Federkun

+0

您必須將$ b初始化爲** public static $ b **。除非你不能使用它。 –

+2

'var $ b;'。你想支持php4?或者你只是閱讀很老的教程? –

回答

0

你應該申報$ B作爲靜態變量。

還要注意方法的類名稱現在已不see the details here

final class repo { 
    public static $b; 

    /** 
    * @var \Guzzle\Http\Client 
    */ 
    protected $client; 

    function repo($myvar) 
    { 
     static::$b = $myvar; 
     $this->client = static::$b; 
    } 
} 
+1

爲什麼你把'static :: $ b = $ myvar;'改成'$ this-> b = $ myvar;'然後呢? – Federkun

+0

@Federkun兩者都是一樣的,它是類的成員,所以我使用了'$ this',但是我們也可以使用作用域分辨率來實現相同的效果。有什麼問題嗎? – Tiger

+0

你試過了嗎? http://stackoverflow.com/questions/151969/when-to-use-self-over-this – Federkun

0

聲明var $b;是PHP 4 PHP 5允許它,它是相當於public $b;

但是,它已過時,如果您使用正確的錯誤報告(開發期間爲error_reporting(E_ALL);),您會收到警告。您應該改用PHP 5 visibility kewords

此外,聲明function repo($myvar)是一種PHP 4構造函數樣式,也被接受但不推薦使用。您應該使用PHP 5 __constructor()語法。

您訪問$bstatic::$b,這與它的聲明(等效,如上所述,與public $b相當)不兼容。如果您希望它是類屬性(這是static所做的),則必須將其聲明爲類屬性(即public static $b)。

將所有內容放在一起,寫上您的課正確的方法是:

final class repo { 
    // public static members are global variables; avoid making them public 
    /** @var \Guzzle\Http\Client */ 
    private static $b; 

    // since the class is final, "protected" is the same as "private" 
    /** @var \Guzzle\Http\Client */ 
    protected $client; 

    // PHP 5 constructor. public to allow the class to be instantiated. 
    // $myvar is probably a \Guzzle\Http\Client object 
    public __construct(\Guzzle\Http\Client $myvar) 
    { 
     static::$b = $myvar; 
     // $this->b probably works but static::$b is more clear 
     // because $b is a class property not an instance property 
     $this->client = static::$b; 
    } 
} 
0

試試這個

final class repo { 
    public $b; 

    /** 
    * @var \Guzzle\Http\Client 
    */ 
    protected $client; 

    function repo($myvar) 
    { 
     $this->b = $myvar; 
     $this->client = $this->b; 
    } 
} 

注:靜態:: /自::靜態函數使用。