views:

68

answers:

3
+1  Q: 

PHP Class Logic

My question is rather simple, given:

class MyClass{
   function a(){
       echo "F.A ";
   }
   function b(){
       echo "F.B ";
   }
}

$c=new MyClass;
$c->a()->b()->b()->a();

So that it will output:

F.A F.B F.B F.A

What changes to code need to be made for this to work, or should it work as is or even just what this is called. If I could get whatever this term is called I could research it mysqlf, but I am not quite sure what to Google.

Thanks in Advance!

+7  A: 

In each function you would have to:

  return $this;
colithium
Returnin `$this` would allow you to carry on the object line ina chain effect, +1 might as well accept this answer.
RobertPitt
Thank you both! That exactly what I was looking for!
Nitroware
+6  A: 

Stringing together methods like that is called "chaining."

return $this; in each method will enable chainability, since it keeps passing the instance from one method to the other, maintaining the chain.

You have to explicitly do this, since PHP functions will return NULL by default.

So, you just need 2 more lines.

<?php
    class MyClass{
   function a(){
       echo "F.A ";
       return $this; // <== Allows chainability
   }
   function b(){
       echo "F.B ";
       return $this;
   }
}

$c=new MyClass;
$c->a()->b()->b()->a();
?>

Live Example

Take a look at this article by John Squibb for a further exploration of chainability in PHP.


You can do all sorts of stuff with chainability. Methods commonly involve arguments. Here's an "argument chain":

<?php
   class MyClass{
   private $args = array();
   public function a(){
       $this->args = array_merge($this->args, func_get_args());
       return $this;
   }
   public function b(){
       $this->args = array_merge($this->args, func_get_args());
       return $this;
   }
   public function c(){
       $this->args = array_merge($this->args, func_get_args());
       echo "<pre>";
       print_r($this->args);
       echo "</pre>";       
       return $this;
   }   
}

$c=new MyClass;
$c->a("a")->b("b","c")->b(4, "cat")->a("dog", 5)->c("end")->b("no")->c("ok");

// Output:
//   Array ( [0] => a [1] => b [2] => c [3] => 4 [4] => cat 
//           [5] => dog [6] => 5 [7] => end )
//   Array ( [0] => a [1] => b [2] => c [3] => 4 [4] => cat 
//           [5] => dog [6] => 5 [7] => end [8] => no [9] => ok )
?>

Live Example

Peter Ajtai
Thank you both! That exactly what I was looking for!
Nitroware
@Nitroware - You're welcome ;)
Peter Ajtai
A: 

Method chaining is used heavily in domain-specific languages and in particular so called "fluent interfaces", coined by Martin Fowler. See his DSL book's pre-print online if you want to explore this expressive programming style. http://martinfowler.com/dslwip/

burkestar