简体   繁体   中英

Use method of parent class when extending

Probably a silly question.. but how do I correctly use the methods of class Test in class Testb without overriding them?

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

You need to give the Testb constructor a $name parameter too if you want to be able to initialize it with that argument. I modified your Testb class so that its constructor actually takes an argument. The way you currently have it, you should not be able to initialize your Testb class. I use the code as follows:

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

Perhaps you do not have error reporting enabled? In any event, you can verify my results here: http://ideone.com/MHP2oX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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