【问题标题】:Can't call parent method properties from inheritance class in php无法从php中的继承类调用父方法属性
【发布时间】:2017-03-12 05:18:32
【问题描述】:

我是 OOP PHP 的初学者。我有这样的代码

class Index 
{
    public $activepage = true;
    public $url;
    public $page;

    function __construct()
    {
        if ($this->activepage) {
            $this->url = "Yes";
            $this->page = "Home";
        } else {
            $this->url = "No";
            $this->page = "Index";
        }

    }


    public function show()
    {
        return $this->page;
    }


    public function showTest()
    {
        return "test";
    }
}

class Home extends Index
{

    function __construct()
    {
        echo $this->show();
    }
}

$page = new Home;

我的问题是: 为什么我调用 Home 类时出现空白页?

但是当我像 echo $this->showTest(); 这样更改 Home 类中的构造函数时,它可以工作。并在屏幕上显示“测试”。

我的 show 方法和 Index 类中的 showTest 方法有什么不同?

【问题讨论】:

  • 你家的物件是不是已经成熟了?

标签: php class oop methods


【解决方案1】:

当您在Home 类中添加__construct() 时,它会覆盖父类Index 的构造。

您可以手动调用父构造:

function __construct()
{
    parent::__construct();
    echo $this->show();
}

【讨论】:

  • 谢谢 Gab。这是工作,对我很有帮助。非常感谢
【解决方案2】:

你可以像这样调用Parent类方法;

parent::show()

【讨论】:

  • 当我把你的答案放在我的家庭类构造函数中时,我仍然有空白屏幕。非常感谢 Pramod 的回答。
猜你喜欢
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
  • 2021-05-07
  • 2019-08-11
  • 2022-01-24
  • 2011-04-30
相关资源
最近更新 更多