Thursday, December 19, 2013

what does return $this mean in php oops ?


This way of coding is called fluent interfacereturn $this returns the current object, so you can call multiple function as single object/line
code like this: do you know about method chaining if no ,then you can find here :)
$object
  ->function1()
  ->function2()
  ->function3()
  ;
instead of:
$object->function1();
$object->function2();
$object->function3();
Here is you can find real example 
<?php

class a{
    public $name='';
    public function setName($name){
        
        $this->name=$name;
        return $this;
    }
      public function getName(){
        
        $this->name;
        return $this;
    }
}


?>
Create an object to call method-chaining
<?php
$obja=new a();
$name=$obja->setName('bikash')->getName();
echo $name->name;
Hope this class may help you :)

No comments:

Post a Comment