大致意思是 $this 沒有上下文,原因是沒有對此類進行實例化。
出現此錯誤的原因是:在FileCommand.php中使用 $this->方法/屬性。
$this 不是不可以用,而是要看情況用。在實例化的 類中使用 $this是可以的
class Person{ private var $name; private var $sex; public function showName(){ echo $this->name; $this->message(); } public function message(){ echo "success"; } }
如果不實例化 Person 類而直接訪問的話就會出上面的錯誤,意思是 $this沒有上下文。
正確用法:
$person = new Person();
$person.showName();
如果不想定義直接用的話,則可通過: Person::message(); 注意里邊不能含有 $this
PHP允許使用static關鍵字,該關鍵字適用於允許在未初始化類的情況下就可以調用的方法;
請注意,在一個靜態方法中,不能使用this關鍵字,因為可能會沒有可以引用的對象實例。
class test { private $a; function t1( ){ $this->a=1; print $this->a.""; } static function t2( ){ $test=new test(); //靜態方法 所以要實例化這個類;而不能直接用 $this-> $test->a=2; print $test->a.""; } } $re= new test( ); $re->t1(); $re::t2();
一般非常量、靜態字段、靜態方法,都是用指向來 -> 來調用內部成員,例如:$re -> t1()
只有常量、靜態字段、靜態方法,采用 :: 調用,例如:$re :: t1()