[英]Accessing parent property inside parent class throws error - using $this when not in object context
[英]Troubleshooting “Using $this when not in object context” when trying to access property of child class from parent class
我有一個主類,它將在主類的函數中初始化另一個類,並且我需要從主類到該另一個類獲取一個變量(在本例中$this->db
)。 例如,我有一個主類Wordle_Admin
:
class Wordle_Admin
{
public function __construct()
{
$this->db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
}
public function views()
{
include 'Wordle_Admin_Views.php';
$wsa = new Wordle_Admin_Views();
$view = @$_GET['view'];
$id = @$_GET['id'];
$type = @$_GET['type'];
$action = @$_GET['action'];
$msg = @$_GET['msg'];
if( !empty( $view ) && method_exists( $wsa, $view ) ):
$wsa::$view($id, $type, $action, $msg);
elseif( !empty( $view ) && !method_exists( $wsa, $view ) ):
echo'View does not exist.';
else:
$wsa::index($id, $type, $action, $msg);
endif;
}
}
我還有另一堂課:
class Wordle_Admin_Views extends Wordle_Admin
{
public function __construct()
{
parent::__construct();
}
public function index( $id = "", $type = "", $action = "", $msg = "" )
{
$this->db->query('SELECT * FROM wordle_post');
}
}
我不能在Wordle_Admin_Views
使用$this->db
,它返回:
致命錯誤:第22行上的C:\\ Server \\ wordle \\ w-includes \\ Wordle_Admin_Views.php中不在對象上下文中時使用$ this
所以我的問題是,如何在父類之間傳遞變量? 我們感謝各種幫助,也可以張開雙手接受關於做不同事情的指示。
您的具體問題是您要靜態調用該方法。 您在靜態上下文中沒有對象,因此不能使用$this
。
您的另一個問題似乎是您對繼承略有誤解。 由於僅當實例化對象( new Worlde_Admin
)時才創建數據庫連接,因此子對象也是如此。
Wordle_Admin_Views
無法自動訪問在Worlde_Admin
某些實例中可能已創建或未創建的數據庫連接。 只有該Worlde_Admin
實例具有該數據庫連接。 您需要實例化Wordle_Admin_Views
,使其也具有連接(因為它繼承了Worlde_Admin
)。
$admin = new Worlde_Admin; // $admin now has its own db connection
$admin2 = new Worlde_Admin; // $admin2 now has another db connection
$view = new Wordle_Admin_Views; // $view has yet another connection
Wordle_Admin_Views::index(); // this has no db connection
您應該研究依賴注入,這意味着您在類之外創建了一個mysqli
實例,並在實例化時將其注入到每個實例中。
$db = new mysqli(...);
$admin = new Worlde_Admin($db);
$view = new Wordle_Admin_Views($db);
在您的世界管理員課程中嘗試一下...
class Wordle_Admin
{
protected $db;
}
那么假設$ this-> db是在父類中定義的,則在調用$ this-> db時應繼承db var。
在我看來,這可能是問題的一部分:
include 'Wordle_Admin_Views.php';
$wsa = new Wordle_Admin_Views();
/* blah blah */
if( !empty( $view ) && method_exists( $wsa, $view ) ):
$wsa::$view($id, $type, $action, $msg);
elseif( !empty( $view ) && !method_exists( $wsa, $view ) ):
echo'View does not exist.';
else:
$wsa::index($id, $type, $action, $msg);
endif;
您正在嘗試訪問靜態函數,而不是訪問類名,而是訪問對象。 它應該是Wordle_Admin_Views::$view()
或$wsa->$view()
Wordle_Admin_Views::$view()
$wsa->$view()
。
您是否實際學習過php,或者您是在假裝它是其他某種語言(python?),而只是“輕而易舉”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.