[英]how to call parent constructor just once in all child instances in php
我正在嘗試開發一個面向對象的PHP應用程序,其中整個PHP應用程序將從MyApplicationBase基類擴展。 但是問題是我只想創建MyApplicationBase的單個實例。 下面的代碼解釋了我的意思
class MyApplicationBase{
static $called=0;
public var $db;
function __construct()
{
self::$called++;
echo "<pre>MyApplicationBase Created ".self::$called." times</pre>";
$this->db=new DatabaseWrapper();
}
}
class ApplicationSecurity extends MyApplicationBase{
function is_logged_in()
{
$res=$this->db->query("user check db query goes here");
return ($res)?true:false;
}
//..... other methods related to ApplicationSecurity class
}
class ApplicationBusinessLogic extends MyApplicationBase{
// business logic methods here which may use base class vars like $db
// this may also use instance of ApplicationSecurity class
}
class ApplicationTemplating extends MyApplicationBase{
protected function outputHeader()
{
require_once('path/to/themes/header.php');
}
protected function outputSidebar()
{
require_once('path/to/themes/siderbar.php');
}
protected function outputMainbody()
{
require_once('path/to/themes/mainbody.php');
$app=new ApplicationBusinessLogic();
$app->initiate();
}
protected function outputFooter()
{
require_once('path/to/themes/footer.php');
}
public function outputTemplate()
{
$this->outputHeader();
$this->outputSidebar();
$this->outputMainbody();
$this->outputFooter();
}
}
//index.php file code starts here--------
$myPhpApplication = new ApplicationTemplating();
$myPhpApplication->outputTemplate();
我的目標是當我創建應用程序實例時,它僅調用“ MyApplicationBase”類的單個實例,而不是多次調用它。 請告訴我如何實現此目標。 我在Google呆了5個小時,但找不到任何解決方案。
我正在嘗試開發一個面向對象的PHP應用程序,其中整個PHP應用程序將從MyApplicationBase基類擴展。
由於PHP具有單一繼承,因此這是進行面向對象的PHP編程的最糟糕的主意。
但是問題是我只想創建MyApplicationBase的單個實例。
由於每個類都是MyApplicationBase,因此您實際上不希望這樣做,因為這意味着您可以在整個應用程序中實例化一個類。
您可能正在尋找的是傳遞的某種ApplicationClass,其中只有一個實例。
至少,如果您從那里擴展了,那么將來至少可以讓您更輕松地拋棄這種“障礙”。
在任何情況下,您都應該針對ApplicationInterface而不是ApplicationClass進行編程,以簡化此操作(這將是必要的)。
當然,最好的辦法是不朝那個方向做任何事情,而只是首先編寫您需要的代碼。
為了只編寫所需的代碼,需要開發測試驅動的。 如果要進行面向對象的編程,為什么不從此開始呢?
好吧,我想您想在這種情況下避免與數據庫的多個連接。 解決方案使用依賴注入很簡單,只需在MyApplicationBase類之外初始化數據庫連接,然后將其作為構造函數參數傳遞(盡管要注意構造器地獄)。 像這樣:
class MyApplicationBase{
static $called=0;
public $db;
function __construct($db)
{
self::$called++;
echo "<pre>MyApplicationBase Created ".self::$called." times</pre>";
$this->db= $d;
}
}
$db = new DatabaseWrapper();
$templating = new ApplicationTemplating($db);
$security = new ApplicationSecurity($db);
您也可以看看一些框架,它們通常帶有一些依賴注入功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.