Php Inheritance

I use the stable version of PHP 5.3, and sometimes I come across very inconsistent behavior. As far as I know in inheritance, all attributes and methods (private, public and protected) in a super class are passed by a child class.

class Foo { private $_name = "foo"; } class Bar extends Foo { public function getName() { return $this->_name; } } $o = new Bar(); echo $o->getName(); //Notice: Undefined property: Bar::$_name in ...\test.php on line 11 

But when the name attribute Foo :: $ _ is defined as "public", it does not give an error. PHP has its own OO rules ???

thanks

Edit: Now everything is clear. Actually, I was thinking about “inheritance”, creating a new class and inheriting all members independent of my ancestor. I did not know the “access” rules, and the inheritance rules are the same.

Edit According to your comments, this snippet should give an error. But it works.

 class Foo { private $bar = "baz"; public function getBar() { return $this->bar; } } class Bar extends Foo {} $o = new Bar; echo $o->getBar(); //baz 
+6
inheritance oop php
source share
3 answers

From PHP Manual :

The visibility of a property or method can be determined by prefixing the declaration with the keywords public , protected or private . Members of a class declared public can be accessed everywhere. Participants declared protected can only be accessed within the class themselves and by the inherited and parent classes. Members declared as private can only be accessed by the class that the member defines.

 class A { public $prop1; // accessible from everywhere protected $prop2; // accessible in this and child class private $prop3; // accessible only in this class } 

And no, this is no different from other languages ​​that implement the same keywords.

Regarding the second piece of code and code:

No, this should not lead to an error, because getBar() inherits from Foo and Foo has visibility for $bar . If getBar() was defined or overloaded in Bar , this did not work. See http://codepad.org/rlSWx7SQ

+12
source share

Your assumptions are incorrect. Protected and public participants are “transferred”. There are no private members. As far as I know, this is typical of many OOP languages.

+3
source share

Private methods and variables cannot be accessed by child classes or externally - only by the class itself. Use Protected if you want the variable to be available to the child, but not accessible to external classes.

+1
source share

All Articles