PHP constructor and destructor


PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.


Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).


Whenever you see a method name start with a double underscore, it is a "magic" method. PHP reserves all methods starting with __ as magic.


PHP Class Constructor


A constructor is a special method that is called by PHP when you create an instance of the class.


PHP class constructor has the following syntax. public function __construct(Optional Parameter) {}


		  		<?php
				   class MyClass { 
				     function __construct() { 
				       echo "I am being constructed."; 
				     } 
				   } 
				          
				   $obj = new MyClass;  
				?>
		  

Example

		  		<?php
		  			 class Person { 
				     private $_firstName; 
				     private $_lastName; 
				     private $_age; 
				          
				     public function __construct( $firstName, $lastName, $age ) { 
				       $this-> _firstName = $firstName; 
				       $this-> _lastName = $lastName; 
				       $this-> _age = $age; 
				     } 
				   } 
				          
				   $p = new Person( "Students", "Empire", 2 ); 
		  		?>
		  

If a class contains a constructor, it is only called if objects are created from that class.


If an object is created from a child class, only the child class's constructor is called.


To make a child class call its parent's constructor call parent::__construct().


Example

		  		<?php
		  			class NameTag {
					       public $Words;
					}

					class Book {
					       public $Name;

					       public function say() {
					               print "Woof!\n";
					       }

					       public function __construct($BookName) {
					               print "Creating a Book: $BookName\n";
					               $this->Name = $BookName;
					       }
					}


					class ComputerBook extends Book {
					       public function say() {
					               print "Computer!\n";
					       }

					       public function __construct($BookName) {
					               parent::__construct($BookName);
					               print "Creating a computer book\n";
					       }
					}
		  		?>
		  

It is better to call parent::__construct() first from the constructor of a child class, in order to set up all the parent's properties.


PHP Class Destructors


Destructors are useful for tidying up an object before it's removed from memory.


You create destructor methods in the same way as constructors, except that you use __destruct() rather than __construct() :


Example

		  		<?php
		  			function __destruct() { 
					    // (Clean up here) 
					} 
		  		?>
		  

PHP destructors is called when an object is deleted. The destructor method, __destruct(), takes no parameters.


Example

		  		<?php
		  			class Book {
					    public $Name;
					    public function say() {
					        print "Woof!\n";
					    }

					    public function __construct($BookName) {
					        print "Creating a Book: $BookName\n";
					        $this->Name = $BookName;
					    }
					    public function __destruct() {
					        print "{$this->Name} is destructing\n";
					    }

					}
					$aBook = new Book("PHP");
		  		?>
		  


Call parent::__destruct()


The key difference is that you should call parent::__destruct() after the local code for the destruction.


Example

		  		<?php
		  			public function __destruct() {
					    print "{$this->Name} is no more...\n";
					    parent::__destruct();
					}
		  		?>
		  

Example

		  		<?php
		  			class Counter
					  {
					    private static $count = 0;

					    function __construct()
					    {
					      self::$count++;
					    }

					    function __destruct()
					    {
					      self::$count--;
					    }

					    function getCount()
					    {
					      return self::$count;
					    }
					  }

					  //create one instance
					  $c = new Counter();

					  //print 1
					  print($c->getCount() . "<br>\n");

					  //create a second instance
					  $c2 = new Counter();

					  //print 2
					  print($c->getCount() . "<br>\n");

					  //destroy one instance
					  $c2 = NULL;

					  //print 1
					  print($c->getCount() . "<br>\n");
		  		?>
		  

Deleting Objects


Calling unset() on an object will call its destructor before deleting the object.


Magic method list


PHP allows you to create three " magic " methods that you can use to intercept property and method accesses:


  • __get() is called whenever the calling code attempts to read an invisible property of the object
  • __set() is called whenever the calling code attempts to write to an invisible property of the object
  • __call() is called whenever the calling code attempts to call an invisible method of the object

visible refers to non-existing property or method or private or protected the property or method.



__get()


__get() specifies what to do when loading an unknown property.


Example

		  		<?php
		  		class Book {
			             public $Name;


			             public function __get($var) {
			                     print "Attempted to retrieve $var and failed...\n";
			             }
			     }
			     $aBook = new Book;
			     print $aBook->Price;
		  		?>
		  

Example

		  		<?php
		  		class Car { 
	              public function __get( $propertyName ) { 
	                echo "The value of '$propertyName' was requested < br / > "; 
	                return "blue"; 
	              } 
	            } 
	                  
	            $car = new Car; 
	            $x = $car->color; 
	            echo "The car's color is $x \n";
		  		?>
		  

__set()


Use __set() method to catch an attempt to set an invisible property to a value, use needs two parameters: the property name and the value to set it to.


It does not need to return a value:


Example

		  		<?php
		  		public function __set( $propertyName, $propertyValue ) { 
				   // (do whatever needs to be done to set the property value) 
				}    
		  		?>
		  

Example

		  		<?php
		  		class Book {
		              public function __set($var, $val) {
		                      print("UPDATE $var = '$val';");
		              }

		      }

		      $book = new Book();
		      $book ->Price= 1.2;
		  		?>
		  

__call()


Use __call() to handle calls to nonexistent methods of a class. The method should then return a value (if any) back to the calling code:


Example

		  		<?php
		  		public function __call( $methodName, $arguments ) { 
				   // (do stuff here) 
				   return $returnVal; 
				}     
		  		?>
		  

Example

		  		<?php
		  		class Book {
		             public function __call($function, $args) {
		                     $args = implode(', ', $args);
		                     print "Call to $function() with args '$args' failed!\n";
		             }
		    	 }

		    		 $aBook = new Book;
		   			  $aBook->nonExistingMethod("foo", "bar", "baz");
				?>
		  		?>
		  

__toString()


__toString() allows you to set a string value for the object.


		  		<?php
		  			class Cat {
             			public function __toString() {
               		      return "This is a cat\n";
             		}
    			 }

   				  $c = new Cat;
  				   print $c;
		  		?>
		  


Example

		  		<?php
		  			 class ObjectTracker
				  {
				    private static $nextSerial = 0;
				    private $id;
				    private $name;

				    function __construct($name)
				    {
				      $this->name = $name;
				      $this->id = ++self::$nextSerial;
				    }

				    function __clone()
				    {
				      $this->name = "Clone of $that->name";
				      $this->id = ++self::$nextSerial;
				    }

				    function getId()
				    {
				      return($this->id);
				    }

				    function getName()
				    {
				      return($this->name);
				    }
				  }

				  $ot = new ObjectTracker("Zeev's Object");
				  $ot2 = clone $ot;

				  //1 Zeev's Object
				  print($ot->getId() . " " . $ot->getName() . "<br>");

				  //2 Clone of Zeev's Object
				  print($ot2->getId() . " " . $ot2->getName() . "<br>");
		  		?>
		  

Example

		  		<?php
		  			class BaseClass {
					    function __construct() {
					        print "In BaseClass constructor\n";
					    }
					}

					class SubClass extends BaseClass {
					    function __construct() {
					        parent::__construct();
					        print "In SubClass constructor\n";
					    }
					}

					class OtherSubClass extends BaseClass {
					    // inherits BaseClass's constructor
					}

					// In BaseClass constructor
					$obj = new BaseClass();

					// In BaseClass constructor
					// In SubClass constructor
					$obj = new SubClass();

					// In BaseClass constructor
					$obj = new OtherSubClass();
		  		?>
		  

Old style constructors are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use __construct() in new code.


Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.


Example

		  		<?php
		  			class MyDestructableClass 
					{
					    function __construct() {
					        print "In constructor\n";
					    }

					    function __destruct() {
					        print "Destroying " . __CLASS__ . "\n";
					    }
					}

					$obj = new MyDestructableClass();
		  		?>
		  

Example

		  		<?php
		  			class A 
					{ 
					    function __construct() 
					    { 
					        $a = func_get_args(); 
					        $i = func_num_args(); 
					        if (method_exists($this,$f='__construct'.$i)) { 
					            call_user_func_array(array($this,$f),$a); 
					        } 
					    } 
					    
					    function __construct1($a1) 
					    { 
					        echo('__construct with 1 param called: '.$a1.PHP_EOL); 
					    } 
					    
					    function __construct2($a1,$a2) 
					    { 
					        echo('__construct with 2 params called: '.$a1.','.$a2.PHP_EOL); 
					    } 
					    
					    function __construct3($a1,$a2,$a3) 
					    { 
					        echo('__construct with 3 params called: '.$a1.','.$a2.','.$a3.PHP_EOL); 
					    } 
					} 
					$o = new A('sheep'); 
					$o = new A('sheep','cat'); 
					$o = new A('sheep','cat','dog'); 
		  		?>
		  




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