tags:

views:

34

answers:

2

I have a method that basically returns the results of a mysql query.

public function getStuff() {
$this->sort = "myColumn ASC";
$query = ... ORDER BY $this->sort;
return $data;
}

I'd like to reuse that result, only with a different sort order, and it seems like I should be able to grab that data in another method, just by calling the original method. Like this:

public function getMoreStuff() {
$this->sort = "anotherColumn DESC";
$this->getStuff();
}

But, while "getStuff()" is returning data as expected, "getMoreStuff()" doesn't return anything. I'm sure it's not necessary to copy the entire query into my second method, but am at a loss on how I can include it. Any guidance would be very appreciated. Thanks!

A: 

One way to do it:

public function getStuff($sort = 'myColumn ASC') {
    $query = "... ORDER BY $sort";
}

Call it from outside your class with variable $sort-values, or from inside of your class with defined method names (like shortcuts.)

chelmertz
Thanks! That definitely works for using different $sort values, but do you know why a query wouldn't the same method would return a value when called on its own, but wouldn't return a value when called as part of another method? I can't figure out why $this->getStuff() doesn't work when called as part of my second method.
jonathonmorgan
+1  A: 

Couple of problems:

  1. When getMoreStuff() calls getStuff(), the $this->sort from getMoreStuff() is being overwritten by the sort order from getStuff(). You can give getStuff() a default sort by using getStuff($sort = "myColumn ASC"), then feeding a different sort order to getStuff() when you need to.

  2. getStuff() is returning the data to getMoreStuff(), which is then not returning the data it just got. You need to use return $this->getStuff(); (or return $this->getStuff("anotherColumn DESC");.

Brock Batsell
Slow typer — sorry for duplicating part of your answer, chelmertz.
Brock Batsell
Worked like a charm -- thanks so much for your help!
jonathonmorgan
@Brock Batsell haha np. You filled in the important 1)
chelmertz