繁体   English   中英

扩展时使用父类的方法

[英]Use method of parent class when extending

可能是一个愚蠢的问题。但是,如何在不覆盖它们的情况下正确使用Testb类中的Test方法呢?

<?php
class Test {

    private $name;

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

    public function getName() {
        return $this->name;
    }

}

<?php

class Testb extends Test {

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

}

<?php

include('test.php');
include('testb.php');

$a = new Test('John');
$b = new Testb('Batman');

echo $b->getName();

如果您希望能够使用该参数对其进行初始化,则还需要给Testb构造函数一个$name参数。 我修改了您的Testb类,以便其构造函数实际上接受一个参数。 当前的方式,您将无法初始化Testb类。 我使用如下代码:

<?php
class Test {

    private $name;

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

    public function getName() {
        return $this->name;
    }

}

class Testb extends Test {

    // I added the $name parameter to this constructor as well
    // before it was blank.
    public function __construct($name) {
        parent::__construct($name);
    }

}

$a = new Test('John');
$b = new Testb('Batman');

echo $a->getName();
echo $b->getName();
?>

也许您没有启用错误报告? 无论如何,您可以在这里验证我的结果: http : //ideone.com/MHP2oX

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM