PHP Private variable access from child

前端 未结 1 1753
难免孤独
难免孤独 2021-01-12 13:01

so I\'m trying to work out an issue I\'m having in designing PHP classes. I\'ve created a base class, and assigned private variables. I have child classes extending this bas

1条回答
  •  有刺的猬
    2021-01-12 14:04

    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!
    

    0 讨论(0)
提交回复
热议问题