bckurera's thoughts

Just another WordPress.com site

__construct() in PHP, OOP with PHP

on March 18, 2013

In PHP it is possible to use the construct method which is really useful, in java we can have several constructor methods and the rule is the method name should be as same as the class name. In PHP the rule is quite different. It uses a special method __construct which is called once an object is created or simply when new operator is used. Therefore this method is also known as “magic method” and it is one of the few magic methods in PHP.

Without further text, following would be an example of using constructor method with in PHP OOP.

class Cube1 {

	private $length;
	private $depth;
	private $height; 
	
	public function __construct() {
		$this->length = 10;
		$this->depth = 10;
		$this->height = 10;
	}
	
	public function getVolume() {
		return ($this->length * $this->depth * $this->height);
	}
}

$box=new Cube1();
echo $box->getVolume();

This looks really simple. How would it be if we need to have more than one constructor methods which can accept arguments.

class Cube1 {

	private $length;
	private $depth;
	private $height; 
	
	public function __construct($a=10,$b=10,$c=10) {
		$this->length = $a;
		$this->depth = $b;
		$this->height = $c;
	}
	
	public function getVolume() {
		return ($this->length * $this->depth * $this->height);
	}
}

$box=new Cube1(10,2.5);
echo $box->getVolume();

$box2=new Cube1(2);
echo $box2->getVolume();

Since in PHP the __construct method cannot be override directly as in Java but there are few techniques to use so that it is possible in the indirect way. Will discuss them in the next post.

It is up to you to use your imagination and creativity to make use the of this feature.

Advertisements

One response to “__construct() in PHP, OOP with PHP

  1. roderickti says:

    Nice post.

    My pence: If I want a object that can be instantiated in different ways my most preferred method is to create a static method in the class for that e.g. where the instantiation code looks something like this Foo::newInstanceWithBar($bar); – where what we get is an instance of Foo with the effects of Bar on it.

Please add your valuable idea below, will make a discussion, thanks !

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: