Learn PHP


PHP Class Inheritance


With inheritance we can create child classes that are based on the parent class.


A child class inherits all the properties and methods of its parent, and it can also add additional properties and methods.


To create a child class that ' s based on a parent class, you use the extends keyword, as follows:


	      		<?PHP
					class Shape { 
					   // (General Shape properties and methods here) 
					} 
					              
					class Circle extends Shape { 
					   // (Circle-specific properties and methods here) 
					}     
				?>
	      

Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.


For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.


This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.


Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.


Example


		  	<?php
		  		class Foo
				{
				    public function printItem($string)
				    {
				        echo 'Foo: ' . $string . PHP_EOL;
				    }
				    
				    public function printPHP()
				    {
				        echo 'PHP is great.' . PHP_EOL;
				    }
				}

				class Bar extends Foo
				{
				    public function printItem($string)
				    {
				        echo 'Bar: ' . $string . PHP_EOL;
				    }
				}

				$foo = new Foo();
				$bar = new Bar();
				$foo->printItem('baz'); // Output: 'Foo: baz'
				$foo->printPHP();       // Output: 'PHP is great' 
				$bar->printItem('baz'); // Output: 'Bar: baz'
				$bar->printPHP();       // Output: 'PHP is great'
		  	?>
		  

Example


		  	<?php
		  		class A {
               // more code here
				}

				class B extends A {
				        // more code here
				}

				class C extends B {
				        // more code here
				}


				$someObj = new A();  // no problems
				$someOtherObj = new B(); // no problems
				$lastObj = new C(); // still no problems
		  	?>
		  

Example


		  	<?php
		  		class foo
				{
				  public function something()
				  {
				    echo __CLASS__; // foo
				    var_dump($this);
				  }
				}

				class foo_bar extends foo
				{
				  public function something()
				  {
				    echo __CLASS__; // foo_bar
				    var_dump($this);
				  }
				}

				class foo_bar_baz extends foo_bar
				{
				  public function something()
				  {
				    echo __CLASS__; // foo_bar_baz
				    var_dump($this);
				  }

				  public function call()
				  {
				    echo self::something(); // self
				    echo parent::something(); // parent
				    echo foo::something(); // grandparent
				  }
				}

				error_reporting(-1);

				$obj = new foo_bar_baz();
				$obj->call();
		  	?>
		  


Example


		  	<?php
		  		abstract class Cheese
				{
				      //can ONLY be inherited by another class
				}

				class Cheddar extends Cheese
				{
				}

				$dinner = new Cheese; //fatal error
				$lunch = new Cheddar; //works!
		  	?>
		  

Example


		  	<?php
		  		trait  custom
				{
				     public function hello()
				     {
				          echo "hello";
				     }
				}

				trait custom2
				{
				       public function hello()
				       {
				            echo "hello2";
				       }
				}

				class inheritsCustom
				{
				        use custom, custom2
				        {
				              custom2::hello insteadof custom;
				        }
				}

				$obj = new inheritsCustom();
				$obj->hello();
		  	?>
		  

Example


		  	<?php
		  		trait tExtend {
				    private $objectExtend = [];

				    final public function extend() {
				        foreach ($objects = func_get_args() as &$object) {
				            if (is_object($object) && !$object instanceOf self) {
				                $this->objectExtend[] = $object;
				                
				                if (is_callable([$object, 'syncExtend']))
				                    $object->syncExtend($this, $objects);
				            }
				        }
				    }

				    final public function syncExtend(&$object = null, array $objects) {
				        if (is_object($object) && !$object instanceOf self && !in_array($object, $this->objectExtend))
				            $this->objectExtend[] = $object;

				        foreach ($objects as &$object)
				            if (is_object($object) && !$object instanceOf self && !in_array($object, $this->objectExtend))
				                $this->objectExtend[] = $object;

				        return $this;
				    }

				    final public function __call($method, $args) {
				        if (method_exists($this, $method))
				            return $this->{$method}(... $args);
				        else {
				            foreach ($this->objectExtend as $i => &$object) {
				                if (method_exists($object, $method))
				                    return $object->{$method}(... $args);
				            }
				        }

				        throw new \Exception('Call to undefined method ' . get_called_class() .  '::' . $method . '()');
				    }

				    final public function __get($key) {
				        if (array_key_exists($key, $this))
				            return $this->{$key};

				        foreach ($this->objectExtend as &$object) {
				            if (array_key_exists($key, $object))
				                return $object->{$key};
				        }

				        trigger_error('Undefined property: ' . get_called_class() . '::$' . $key, E_USER_NOTICE);
				    }

				    final public function __isset($key) {
				        if (array_key_exists($key, $this))
				            return true;

				        foreach ($this->objectExtend as &$object) {
				            if (array_key_exists($key, $object))
				                return true;
				        }

				        return false;
				    }
				}

				/*************/

				class F {
				    public $relationship = 'Sister';
				}

				class M {
				    public $relationship = 'Brother';
				}

				class A extends M {
				    use tExtend;
				}
				class B extends F {
				    use tExtend;

				    function getName() {
				        return 'B';
				    }
				}
				class C extends F {
				    use tExtend;

				    function getName() {
				        return 'C';
				    }
				}
				class D extends M {
				    use tExtend;
				}

				class Z  {
				    use tExtend;

				    function getParent() {
				        return 'Z';
				    }

				    function __construct() {
				        $this->extend(... func_get_args());
				    }
				}

				$a = new A;
				$b = new B;
				$c = new C;
				$d = new D;
				$z = new Z($a, $b, $c, $d);

				$d->extend($a); // Change nothing
				$a->varA = 'A';
				$c->varA = 'C';

				echo $a->getParent(); // print Z
				echo $a->getName(); // print B
				echo $b->getName(); // print B
				echo $c->getName(); // print C
				echo $d->getName(); // print B
				echo $z->getName(); // print B
				echo $z->varA; // print A
				echo $c->varA; // print C
		  	?>
		  

Example


		  	<?php
		  		class Animal
				  {
				    public $blood;
				    public $name;

				    public function __construct($blood, $name=NULL)
				    {
				      $this->blood = $blood;
				      if($name)
				      {
				        $this->name = $name;
				      }
				    }
				  }

				  class Mammal extends Animal
				  {
				    public $furColor;
				    public $legs;

				    function __construct($furColor, $legs, $name=NULL)
				    {
				      parent::__construct("warm", $name);
				      $this->furColor = $furColor;
				      $this->legs = $legs;
				    }
				  }

				  class Dog extends Mammal
				  {
				    function __construct($furColor, $name)
				    {
				      parent::__construct($furColor, 4, $name);
				      self::bark();
				    }

				    function bark()
				    {
				      print("$this->name says 'woof!'");
				    }
				  }

				  $d = new Dog("Black and Tan", "Angus");
		  	?>
		  


Example


		  	<?php
		  		class Calculator {
				  protected $_val1, $_val2;

				  public function __construct( $val1, $val2 ) {
				    $this->_val1 = $val1;
				    $this->_val2 = $val2;
				  }

				  public function add() {
				    return $this->_val1 + $this->_val2;
				  }

				  public function subtract() {
				    return $this->_val1 - $this->_val2;
				  }

				  public function multiply() {
				    return $this->_val1 * $this->_val2;
				  }

				  public function divide() {
				    return $this->_val1 / $this->_val2;
				  }
				}

				class CalcAdvanced extends Calculator {
				  private static $_allowedFunctions = array( "pow" => 2, "sqrt" => 1, "exp" => 1 );

				  public function __construct( $val1, $val2=null ) {
				    parent::__construct( $val1, $val2 );
				  }

				  public function __call( $methodName, $arguments ) {
				    if ( in_array( $methodName, array_keys( CalcAdvanced::$_allowedFunctions ) ) ) {
				      $functionArguments = array( $this->_val1 );
				      if ( CalcAdvanced::$_allowedFunctions[$methodName] == 2 ) array_push( $functionArguments, $this->_val2 );
				      return call_user_func_array( $methodName, $functionArguments );
				    } else {
				      die ( "<p>Method 'CalcAdvanced::$methodName' doesn't exist</p>" );
				    }
				  }
				}
				$ca = new CalcAdvanced( 3, 4 );
				echo "<p>3 + 4 = " . $ca->add() . "</p>";
				echo "<p>3 - 4 = " . $ca->subtract() . "</p>";
				echo "<p>3 * 4 = " . $ca->multiply() . "</p>";
				echo "<p>3 / 4 = " . $ca->divide() . "</p>";
				echo "<p>pow( 3, 4 ) = " . $ca->pow() . "</p>";
				echo "<p>sqrt( 3 ) = " . $ca->sqrt() . "</p>";
				echo "<p>exp( 3 ) = " . $ca->exp() . "</p>";
		  	?>
		  

PHP Overriding Methods


To create a child class whose methods are different from the corresponding methods in the parent class by overriding a parent class's method in the child class.


To do this, simply create a method with the same name in the child class. Then, when that method name is called for an object of the child class, the child class's method is run instead of the parent class's method:


		  	<?php
			class ParentClass { 
			  public function someMethod() { 
			    // (do stuff here) 
			  } 
			} 
			     
			class ChildClass extends ParentClass { 
			  public function someMethod() { 
			    // This method is called instead for ChildClass objects 
			  } 
			} 

			$parentObj = new ParentClass; 
			$parentObj->someMethod();  // Calls ParentClass::someMethod() 
			$childObj = new ChildClass; 
			$childObj->someMethod();   // Calls ChildClass::someMethod()  
			?>
		  

Preserving the Functionality of the Parent Class


To call an overridden method, you write parent:: before the method name: parent::someMethod();


		  	<?php 
			    class Fruit { 
			      public function peel() { 
			        echo "peeling the fruit.\n"; 
			      } 
			      public function slice() { 
			        echo "slicing the fruit.\n"; 
			      } 
			            
			      public function eat() { 
			        echo "eating the fruit. \n"; 
			      } 
			            
			      public function consume() { 
			        $this-> peel(); 
			        $this-> slice(); 
			        $this-> eat(); 
			      } 
			    } 
			    class Banana extends Fruit { 
			        public function consume() { 
			          echo " < p > I'm breaking off a banana... < /p > "; 
			          parent::consume(); 
			        } 
			     } 

			     $apple = new Fruit; 
			     $apple->consume(); 
			                 
			     $banana = new Banana; 
			     $banana->consume();   
			                     
			?>  
		  

PHP final Classes and Methods


To lock down a class so that it can't be inherited from. Or to lock down one or more methods inside a class so that they can't be overridden in a child class.


By doing this, you know that your class or methods within your class will always behave in exactly the same way.


You can add the keyword final before a class or method definition to lock down that class or method.


		 	final class MyClass { 

			} 
		 

		 	class ParentClass { 
			   public final function myMethod() { 
			            echo "A method"; 
			   } 
			} 
		 




PHP Tutorials


Home

Introduction

Syntax

Variable

Comment

Echo and Print Statement

Data Types

Boolean

Integer

Number Convert

PHP String

php variable substitution in string

php string element

php string function

php addcslashes function

php addslashes function

php get magic quotes gpc function

php get meta tags function

php urlencode function

PHP $ and $$ Variables

PHP constant

PHP Magic Constants

PHP Static Variable

PHP Super Globals

PHP Globals

PHP Server

PHP reserved variable get

PHP reserved variable post

PHP reserved variable FILES

PHP reserved variable Cookies

PHP reserved variable Session

PHP reserved variable Request

PHP reserved variable environment

PHP Operator

PHP Arithmetic Operator

PHP Comparison Operator

PHP Incrementing and Decrementing Operators

PHP Identical Operators

PHP Logical Operators

PHP String Operators

PHP Ternary Operators

PHP Execution Operators

PHP Operator Precedence

PHP Array Operator

PHP Class

PHP Class Inheritance

PHP constructor and destructor

PHP abstract class

PHP class access control

PHP statement

PHP If statement

PHP else statement

PHP else if statement

PHP control structure statement

PHP while loop

PHP do while loop

PHP for loop

PHP for each loop

PHP break statement

PHP continue statement

PHP declare statement

PHP return statement

PHP require statement

PHP include

PHP require once

PHP include once

PHP goto statement

PHP function

PHP function parameter

PHP function scope

PHP array

PHP array operator

PHP array element loop

PHP array foreach loop

PHP array multidimensional

PHP html forms

PHP get and post method

form redirect

file inclusion

file i/o