我有這種方法,我想使用$ this,但我得到的是:致命錯誤:使用$ this而不是在對象上下文中。在靜態函數中使用這個失敗
我該如何得到這個工作?
public static function userNameAvailibility()
{
$result = $this->getsomthin();
}
我有這種方法,我想使用$ this,但我得到的是:致命錯誤:使用$ this而不是在對象上下文中。在靜態函數中使用這個失敗
我該如何得到這個工作?
public static function userNameAvailibility()
{
$result = $this->getsomthin();
}
這是正確的做法
public static function userNameAvailibility()
{
$result = self::getsomthin();
}
使用self::
,而不是$this->
爲靜態方法。
參見:PHP Static Methods Tutorial更多信息:)
不能使用$this
靜態函數內部,因爲靜態函數是獨立於任何實例化對象。 嘗試使該功能不是靜態的。
編輯: 根據定義,靜態方法可以被稱爲無任何實例化的對象,因此,存在是一個靜態方法內沒有有意義的使用的$this
。
應該有,當你試圖分配靜態變量爲一個實例變量。這不是可能嗎? – Jom 2010-02-18 06:27:15
訪問者this
引用類的當前實例。由於靜態方法不會從實例運行,因此禁止使用this
。所以需要直接在這裏調用該方法。靜態方法無法訪問實例範圍內的任何內容,但訪問實例範圍外的類範圍內的所有內容。
只有靜態功能可以使用自靜態函數::中被調用,如果你的類包含了要使用,那麼你可以聲明實例非靜態函數並且使用它。
<?php
class some_class{
function nonStatic() {
//..... Some code ....
}
Static function isStatic(){
$someClassObject = new some_class;
$someClassObject->nonStatic();
}
}
?>
很遺憾PHP沒有顯示足夠的描述性錯誤。你不能在一個靜態函數中使用$ this->,而是使用self ::如果你必須調用同一個類中的函數
這裏是一個例子,說明當一個類的方法被調用時一個錯誤的方式。執行此代碼時您會看到一些警告,但它會起作用並將打印:「我是A:打印B屬性」。 (在php5.6執行的處理)
class A {
public function aMethod() {
echo "I'm A: ";
echo "printing " . $this->property;
}
}
class B {
public $property = "B property";
public function bMethod() {
A::aMethod();
}
}
$b = new B();
$b->bMethod();
它接縫變量$這一點,在一個方法中使用,其被稱爲靜態方法,指向「呼叫者」類的實例。在上面的例子中有$這個 - >屬性,在A類中使用,它指向B.
編輯的屬性:
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). PHP > The Basics
是的,我正要發佈這個答案。 – 2010-02-18 06:25:46
您還應該記住,getsomthin()方法也必須是靜態的 - 您不能在靜態方法內調用非靜態方法。 – thorinkor 2013-07-09 10:10:32
@Sarfraz,不應該是'static ::'而不是'self ::'嗎? – Pacerier 2013-07-30 10:18:19