Method Chaining is the new feature of object-oriented approach introduced in PHP5.Today I am going to explain how to use method chaining in PHP5.
Method Chaining is like to call method in chain means we can call more than one methods using single instance.
Let’s see the SYNTAX of Method Chaining:
1 2 3 | $obj->method1()->method2()->method3(); |
Above Syntax explains that method1()
will return an object and method2()
will send the result of method1() and then method2() will pass the return value to method3().
To implement Method Chaining, You must have to return object value from methods.The returned object not to be the same one from which the method is being called.
If you have worked with CodeIgniter Framework, you must have idea about the method chaining.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | class ResizeImage { public $image_type; public $image_width; public $image_height; { $image_info = getimagesize($file); $this->image_type = $image_info['mime']; { $this->image = imagecreatefromjpeg($file); } elseif ($this->image_type == 'image/png') { $this->image = imagecreatefrompng($file); } return $this; } function getWidth() { $this->image_width = imagesx($this->image); return $this; } function getHeight() { $this->image_height = imagesy($this->image); return $this; } function resizeImgWidthHeight($width,$height) { if($height > $width){ $img_ratio = $width / $this->getWidth()->image_width; $height = $this->getheight()->image_height * $img_ratio; }else{ $img_ratio = $height / $this->getHeight()->image_height; $width = $this->getWidth()->image_width * $img_ratio; } $resized_image = imagecreatetruecolor($width, $height); imagecopyresampled($resized_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth()->image_width , $this->getHeight()->image_height); $this->image = $resized_image; return $this; } function save($file, $image_type = 'image/jpeg', $compression = 75) { if ($image_type == 'image/jpeg') { imagejpeg($this->image, $file, $compression); } elseif ($image_type == 'image/png') { imagepng($this->image, $file); } } } |
Use Object:
1 2 3 4 5 | $obj = new ResizeImage(); $obj->loadImg('background.jpg')->getWidth()->getHeight()->resizeImgWidthHeight(90,90)->save('new_background.jpg'); print_r($obj); |
Here, I have created one class for resizing an image and created an object of the class and called all methods in chain which will resize image and save into folder.
That’s it.It is important to note that the method chaining require to return the object and can’t return any other values then the object.
Also Read:
Static Keyword in PHP
Constructor and Destructor in PHP
Type Hinting in PHP5
Hope this article helpful to you.As always, thanks for reading an article. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.