Questionable private $varname behavior

php.internals

Greg Beaver

23 years ago
Hi, a discussion on php.general led to the discovery of this oddly legal script: <?php class dog { // declare two private variables private $Name; private $DogTag; public function bark() { print "Woof!\n"; } public function printName() { print $this->Name; // prints nothing! } } // new class, for testing derived stuff class poodle extends dog { public function bark() { print "Yip!\n"; } } // I now create an instance of the // derived class $poppy = new poodle; // and set its private property $poppy->Name = "Poppy"; print $poppy->Name. "\n"; $poppy->printName(); print_r($poppy); ?> outputs: Poppy poodle Object ( [Name:private] => [DogTag:private] => [Name] => Poppy ) Is this expected behavior or should I open a bug? Greg

Andi Gutmans

23 years ago
At 07:27 PM 11/7/2003 -0400, Greg Beaver wrote:
>Hi, a discussion on php.general led to the discovery of this oddly legal >script: > ><?php > class dog { > // declare two private variables > private $Name; > private $DogTag; > > public function bark() { > print "Woof!\n"; > } > > public function printName() { > print $this->Name; // prints nothing! > } > } > > // new class, for testing derived stuff > class poodle extends dog { > public function bark() { > print "Yip!\n"; > } > } > > // I now create an instance of the > // derived class > $poppy = new poodle; > > // and set its private property > $poppy->Name = "Poppy"; > print $poppy->Name. "\n"; > $poppy->printName(); > print_r($poppy); >?> > >outputs: > >Poppy >poodle Object >( > [Name:private] => > [DogTag:private] => > [Name] => Poppy >) > >Is this expected behavior or should I open a bug?
Seems to be expected behavior to me. poodle doesn't *know* the private variable "Name" so when you use $poppy->Name it declares a public member instead. As printName() is inherited from the base class it accesses the private member and not the public one. Andi