/** * Instances CANNOT use private and protected members * Children CAN inherit only public and protected members */ class MyClass { public $name = 'John'; protected $username = 'JohnT23'; private $password = 'secret'; function printAll() { echo "From class MyClass:"; echo $this->name." "; echo $this->username." "; echo $this->password." "; } } $obj = new MyClass(); echo "From Instance \$obj:".$obj->name."\n"; //Works //echo $obj->username; // Fatal Error //echo $obj->password; // Fatal Error $obj->printAll(); echo"\n<br>"; class MyClass2 extends MyClass { // We can re-declare/access the public and protected method // but not private ones function printAll() { echo "From class MyClass2:"; echo $this->name." "; echo $this->username." "; // Children cannot access private member of parent // echo $this->password; // Error } } $obj2 = new MyClass2(); echo "<br> From Instance \$obj2:".$obj2->name; // Works //echo $obj->username; // Fatal Error //echo $obj->password; // Fatal Error $obj2->printAll();
Monday, March 3, 2014
OOP Basics
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment