I have a class function that queries data like so:
// Disclaimer: (None of the following is "real")
class Mockup {
function getData() {
query("SELECT id,name FROM pages")
// Results: $id = 1, $name = "Math Text Book: Grade 7"
}
}
Though I'd like to be able to access both values (That is, $id and $name), I can only return one value individually (Thus creating a disadvantage when compared to simply querying outside of the class).
Would something along the lines of the following be possible in conjunction with the above example code?
$test = new Mockup;
echo $test->getData()->id; // Echos "7"
Similarly, I've seen something along the lines of the following in various software such as MediaWiki:
$test = new Mockup;
echo $test->getData()->getId(); // Echos "7"
Is that an indication that it's also possible to nest functions as well?
That's not an embedded function it's method chaining. When a method returns the class instance, you can use it to immediately use another class member (var or function), thus chaining them together.
class Mockup {
public $id;
public $name;
function getData() {
$data = query();
$this->id = $data->id;
$this->name = $data->name;
return $this; // return the instance for chaining
}
function getId() {
return $this->id;
}
function getName() {
return $this->name;
}
}
$mockup = new Mockup();
//unchained
$mockup->getData();
$id = $mockup->getId();
$name = $mockup->getName();
// or
$id = $mockup->id;
$name = $mockup->name;
//chained
$id = $mockup->getData()->getId();
$name = $mockup->getData()->getName();
//or
$id = $mockup->getData()->id;
$name = $mockup->getData()->name;
If you want to return both at once you could simply return an array or an object containing those values.
FYI: When using chaining you don't have to return the instance of the class you are calling the method from, you can also in that method, create a new instance of another class and return that, so you can call members from that instance, for example:
$garage->getVehicle('plane')->fly(); // returns new Plane() with specific methods
$garage->getVehicle('car')->drive(); // returns new Car() with specific methods