3

Possible Duplicate:
PHP method chaining?

I want to use functions combined, like:

select("SELECT * FROM users").where("user=l0 ").join(" . . . ");

How to define this in php?

Community
  • 1
  • 1
  • 2
    I feel I should warn you that this kind of thing is a *lot* harder to write than it looks. The simple example you've given won't be hard to achieve, but also won't achieve much (you might just as well write the query as a string). If you want it to do anything clever, it will be a very big project. – Spudley Nov 01 '12 at 20:00

2 Answers2

4
function select(){
     ....
     return new myType;
}

class myType {

     function where(){
         ...
         return $this;
     }

     function join(){
         ...
         return $this;
     }

}

Demo: http://codepad.org/pyrIEW0t

Remember to use -> instead of . in PHP.

This is an example of PHP function chaining.

hakre
  • 193,403
  • 52
  • 435
  • 836
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • @user1792423 you don't unless you are just concatting strings (which I do not think you want to do). – Naftali Nov 01 '12 at 20:11
1

The function returns a string and you concatenate the return values of multiple functions.

function select($input) {

//process $input

return $output;

}

function where($input) {

//process $input

return $output;

}

In your php you can call these functions and get the returning result concatenated.

footy
  • 5,803
  • 13
  • 48
  • 96