CONSTRUCTOR

  • PHP 5 allows developers to declare constructor methods for classes.
  • Constructor is suitable for any initialization that the object may need before it is used.
  • We can design constructor using "__construct" or same name as class name.
  • 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().

Example 1

snippet
<?php
	class Example
	{
		public function __construct()
		{
			echo "Hello javatpoint";
		}
	}
	$obj = new Example();
	$obj = new Example();
?>

Output:

CONSTRUCTOR

Example 2

snippet
<?php
	class demo
	{
		public function demo()
		{
			echo "constructor1...";
		}
	}
	
	class demo1 extends demo
	{
		public function __construct()
		{
			echo parent::demo();
			echo "constructor2...";
		}
	}
	$obj= new demo1();
?>

Output:

CONSTRUCTOR
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents