Re: issue with inheriting private property from abstract class

From: Date: Wed, 23 Jun 2004 22:35:14 +0000
Subject: Re: issue with inheriting private property from abstract class
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-188920@lists.php.net to get a copy of this message
ok, i understand now that private members are NOT inherited. i guess it was just throwing me off that var_dump()/print_r() display the parents private member, even tho its not really a member of the subclass. thanks Marek Kilimajer wrote:
Chris wrote --- napísal::
if anyone can, would you please explain why the below code does what it does? I would expect $this->test in TestInstance to refer to the inherited $test from Test. Using php5RC3. Thanks. <?php abstract class Test {
    private $test;
    abstract public function addToTest($i);
} class TestInstance extends Test {
    public function __construct() {
        $this->test = 0;
    }
    public function addToTest($i) {
        $this->test += $i;
    }
} $t = new TestInstance(); $t->addToTest(3); var_dump($t); // test var SHOULD be private echo "private test (shouldn't be able to access it directly, but i can): ".$t->test."\n\n"; /* output ------------------------------- object(TestInstance)#1 (2) { ["test:private"]=> NULL ["test"]=> int(3) } private test (shouldn't be able to access it directly, but i can): 3 */ ?>
The variable is private for Test, so TestInstance does not have access to it. By assigning 0 to $this->test in the constructor of TestInstance, you create a new property of TestInstance that is public (the default). var_dump() shows it clearly: object(TestInstance)#1 (2) { ["test:private"]=> NULL <---- belongs to Test
  ["test"]=> int(3)         <---- belongs to TestInstance
}


« previous php.general (#188920) next »