簡體   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