tags:

views:

70

answers:

3

I have this code:

$db->get()->query()

Now i want the get method's return to depend on:

$db->get()
return $db->query var;

but

$db->get()->query()

the get() method will return $this

+1  A: 

I am not sure what you are asking but

$db->get()->query()

is the same as :

$somevar = $db->get();
$somevar->query();
Iznogood
+3  A: 

Updated: You can't change the return depending on whether you've chained the code (which is what it looks like you want to do) - however for this particular problem you can implement the too string method which will 'appear' to do the same thing :)

<?php
class DB {

  private $query = 'some query';

  public function get()
  {
    return $this;
  }

  public function query()
  {
    // do the query function
  }

  public function __toString()
  {
     return $this->query;
  }
}

$db = new DB;
echo $db->get(); //prints 'some query'
$db->get()->query(); // runs the query() method
nathan
Yes but `$db->get();`(no query() function) will return $this->query; :D
Snoob
Thanks, now my answers is using __tostring(): class DB { private $query = 'some query'; public function __tostring(){ return $this->query; } public function get() { return $this; } public function query() { query ..... } } $db = new DB; echo $db->get()->query(); //Return result from query; echo $db->get() // Return toString
Snoob
@Snoob likewise ;)
nathan
@Snoob, note the get() method is now pointless.. you could remove it
nathan
@nathan: No. echo $db->get() -> will return $this object, but my way is return $this->query;
Snoob
+1  A: 

The function doesn't know the calling context, eg. $x = $db->get(); or $db->get()->query(); So it doesen't know what to return. Make another function or add a param, if you really have to use it like that.

andrem