【问题标题】:PHP __construct() inheritance not workingPHP __construct() 继承不起作用
【发布时间】:2017-05-11 08:07:44
【问题描述】:

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

我有以下 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();

现在,上述解决方案有效,但它并不是我真正需要的。 我需要系统类 __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';
        }

【问题讨论】:

  • $this->在您实例化系统时域未定义
  • 一开始System::__construct不带参数
  • I want to be able to set the domain from my constructor, like so: [...] - 是什么阻止了你?这是一个合理的更改,如果您正确解释了您的问题,应该按照您的意愿进行更改(如果您在所有必要的地方进行更改)。

标签: php oop inheritance subclass


【解决方案1】:

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

 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2015-03-04
    • 2012-06-04
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    相关资源
    最近更新 更多