PHP Private variable access from child

15,518

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!
Share:
15,518
iLoch
Author by

iLoch

Updated on June 04, 2022

Comments

  • iLoch
    iLoch almost 2 years

    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 base class, which make reference and changes to these private variables through functions of the base class. Here's an example, keep in mind I'm still confused about the difference between private and protected methods/variables (let me know if I'm doing it wrong!):

    base.class.php

    <?php
    class Base {
        private $test;
        public function __construct(){
            require('sub.class.php');
            $sub = new Sub;
            echo($this->getTest());
        }
        public function getTest(){
            return $this->test;
        }
        protected function setTest($value){
            $this->test = $value;
        }
    }
    ?>
    

    sub.class.php

    <?php
    class Sub extends Base {
        public function __construct(){
            parent::setTest('hello!');
        }
    }
    ?>
    

    So I'd expect the result to be hello! printed on the screen - instead there is nothing. There could be a fundamental misunderstanding of classes on my part, or maybe I'm just doing something wrong. Any guidance is very much appreciated! Thanks.

    EDIT:

    Thank you to everyone who contributed an answer - I think, despite the excellent solutions, that child classes are actually not what I need - it seems delegate classes may be more useful at this point, as I don't really need to reference the Base functions from within the other classes.