【问题标题】:How to call parent constructor in PHP OOP? [duplicate]如何在 PHP OOP 中调用父构造函数? [复制]
【发布时间】:2023-03-21 04:28:01
【问题描述】:

我正在构建一个基于 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 \Bramus\Router\Router();
        $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 类的所有属性。如果我使用继承,这就是我会发生的事情。

谁能帮我实现这个目标?

【问题讨论】:

    标签: php class oop constructor


    【解决方案1】:

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

    public function __construct($Settings){
        $this->Router = new \Bramus\Router\Router();
        $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
    }
    

    【讨论】:

    • 谢谢,它有效。现在,如果我继续嵌套,只要我的 __construc 函数调用它的父函数,我应该能够尽可能多地嵌套正确吗?
    • 是的,但是你必须关心你的父构造函数的参数。例如,如果您想添加一个扩展 Application 的类 CliApplication,则必须在 CliApplication 构造函数中使用:parent::__construct($Settings);
    猜你喜欢
    • 2010-12-26
    • 2023-03-15
    • 2010-12-06
    • 1970-01-01
    • 2023-03-15
    • 2011-03-06
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    相关资源
    最近更新 更多