PHP __construct() 继承无效

PHP __construct() inheritance not working

我一直在用头撞墙一个多小时,在互联网上寻找解决方案(包括Whosebug),但找不到任何帮助,所以我决定问问你们。

我有以下 classes.php 文件

<?php

class System {

    public $domain;

    public function __construct() {
        $this->domain = 'http://google.com';
    }

    public function getDomain() {
        echo $this->domain;
    }

}

class User extends System {

    public function __construct() {
        parent::__construct($this->domain);
    }

    public function getDomain() {
        echo $this->domain;
    }

}

我的 index.php 文件代码是:

$system = new System();
$user = new User();
$system->getDomain();
$user->getDomain();

现在,上述解决方案有效,但并不是我真正需要的。 我需要系统 class __construct() 如下所示:

public function __construct($domain) {
        $this->domain = $domain;
    }

而且我希望能够从 index.php 页面动态设置域,例如:

$system = new System('http://google.com');

所以回顾一下:

我希望能够从我的构造函数中设置域,如下所示:

public function __construct($domain) {
        $this->domain = $domain;
    }

而不是

public function __construct() {
            $this->domain = 'http://google.com';
        }

其实我不太明白你想做什么,但我会这样做。

 class System {

        private $domain;

        protected function __construct($domain) {
            $this->domain = $domain;
        }

        protected function getDomain() {
            return $this->domain;
        }

    }

    class User extends System {

        public function __construct($domain) {
            parent::__construct($domain);
        }


    }

$user = new User('http://google.com');
echo $user->getDomain();