note 44629 deleted from keyword.parent by aidan

From: Date: Wed, 11 Aug 2004 14:04:32 +0000
Subject: note 44629 deleted from keyword.parent by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-74441@lists.php.net to get a copy of this message
Note Submitter: geoff@hoffmans.net ---- Object-oriented programming examples are always so obscurely written, with $A and $foo. Here's something that I came up with that is a more concrete, real-world example. <?php /**********************************************\ * Demonstration of Object Inheritance in PHP4 * www.salientdigital.com \**********************************************/ // You would most likely place these two // class definitions in an include file. // basic class others inherit from class basic{ var $schooltype; var $level; function basic( $lv ){ $this->schooltype = "High School"; $this->level = $lv; } function hello(){ return "Yo teacher!"; } function chat(){ return $this->hello() . " I'm a ". $this->level ." in ". $this->schooltype ."."; } } // The advanced class inherits from basic plus has extra features class advanced extends basic { var $degree; var $creditbalance; // class constructor function advanced ( $lv, $dg , $cb ) { // Call the parent class constructor first // here is where the inheritance takes place $this->basic($lv); // parent::basic($lv); // works too $this->schooltype = "College"; $this->degree = $dg; $this->creditbalance = $cb; } function hello(){ // overrides the hello() method defined in basic class return "Good afternoon, Professor."; } function chat(){ // shows why you need the parent:: syntax -- // so you can call it in a method that overrides the base class. return parent::chat() ."<br>". " I'm only ". $this->creditbalance . " credits shy of my ". $this->degree ."."; } } // Now that the class definitions are out of the way... // Here is the answer to // 'What is the advantage of Object Oriented Programming?'... // Look at how short and elegant this code is: $Student1 = new basic("Sophomore"); $Student2 = new advanced("Senior", "MBA", 4); echo $Student1->chat() ."<br><br>"; echo $Student2->chat() ; /***** OUTPUT * SHOWN * BELOW ************************\ Yo teacher! I'm a Sophomore in High School. Good afternoon, Professor. I'm a Senior in College. I'm only 4 credits shy of my MBA. \******************************************************/ ?>

« previous php.notes (#74441) next »