PHP Private variable access from child

蓝咒 提交于 2019-12-01 05:47:28

Should be like this:

base.class.php:

class Base {
    private $test;
    public function __construct() {
        echo $this->getTest();
    }
    public function getTest() {
        return $this->test;
    }
    protected function setTest($value) {
        $this->test = $value;
    }
}

sub.class.php:

class Sub extends Base {
    public function __construct() {
        parent::setTest('hello!');  // Or, $this->setTest('hello!');
        parent::__construct();
    }
}

main code:

require 'base.class.php';
require 'sub.class.php';

$sub = new Sub;  // Will print: hello!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!