jonathanatx
jonathanatx

Reputation: 1613

Reuse method within a class

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!

Upvotes: 0

Views: 339

Answers (2)

Brock Batsell
Brock Batsell

Reputation: 5803

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");.

Upvotes: 1

chelmertz
chelmertz

Reputation: 20601

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.)

Upvotes: 0

Related Questions