php運行報錯:Using $this when not in object context
php運行報錯:Using $this when not in object context
以下是我的代碼:
錯誤代碼實例:
public static function getInfo() { // ... 省略部分代碼 $info = $this->getUser(); return $info; } public function getUser() { return [ 'userName': => '小明', 'age' => 17 ]; }
原因分析:
getInfo是靜態函數,$this無法使用,應該把getUser函數變成靜態函數,或者把 getInfo 函數變成非靜態函數
解決:
1. getUser 函數變成靜態函數,$this使用self代替
public static function getInfo() { // ... 省略部分代碼 $info = self::getUser(); return $info; } public static function getUser() { return [ 'userName': => '小明', 'age' => 17 ]; }
2. 把 getInfo 函數變成非靜態函數
public function getInfo() { // ... 省略部分代碼 $info = $this->getUser(); return $info; } public function getUser() { return [ 'userName': => '小明', 'age' => 17 ]; }