如何在PHP OOP中调用父构造函数



我正在构建一个基于web和cli的应用程序。由于cli包含web所需的函数,因此我希望将两者嵌套在一起。

<?php
class API {
protected $Settings;
protected $Database;
protected $FTP;
protected $LDAP;
protected $Auth;
protected $Alerts;
public function __contruct(){
date_default_timezone_set($site['timezone']);
if($Settings['debug']){ error_reporting(-1); } else { error_reporting(0); }
$this->Settings = $Settings;
$this->Alerts = array();
$this->Database = new DB($Settings['sql']['host'], $Settings['sql']['username'], $Settings['sql']['password'], $Settings['sql']['database']);
$this->FTP = new FTP($Settings['ftp']['username'],$Settings['ftp']['password'],$Settings['ftp']['host']);
$this->LDAP = new LDAP($Settings['ldap']['username'],$Settings['ldap']['password'],$Settings['ldap']['host'],$Settings['ldap']['port'],$Settings['ldap']['domain'],$Settings['ldap']['base'],$Settings['ldap']['branches']);
$this->Auth = new Auth();
}
}
class Application extends API {
protected $Router;
protected $URL;
protected $fullURL;
public function __construct($Settings){
$this->Router = new BramusRouterRouter();
$this->URL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")."://".$_SERVER['HTTP_HOST'].'/';
$this->fullURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")."://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
}

但是,当我使用$App = new Application($Settings);创建应用程序时,似乎只有application构造函数在运行。但是我正在尝试获取应用程序类中API类的所有属性。我想如果我使用继承的话会发生这种情况。

有人能帮我实现这一点吗?

Application类的构造函数中,您必须显式调用父构造函数:

public function __construct($Settings){
$this->Router = new BramusRouterRouter();
$this->URL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")."://".$_SERVER['HTTP_HOST'].'/';
$this->fullURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")."://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
parent::__construct(); // <- Add this
}

最新更新