March 2, 2012
Calling a method of an instance of a class
Question by Joe
Forgive me for asking such a novice question, but I can’t figure out how to call a method in PHP. Here’s what I’m trying to do (in pseudocode):
class Thing {
public string Color() {
return "taupe";
}
}
Thing x = new Thing();
echo x.Color();
This should echo taupe
as its result. The part I’m getting stuck on is the last line: invoking the Color
method of x
. How does one do this in PHP?
Answer by Jemaclus
In PHP, you would do something like:
class Thing {
public function color() {
return "taupe";
}
}
$thing = new Thing;
echo $thing->color();
You were close 🙂
I suggest reading up on PHP’s OOP information here. They’ve got a lot of good information about how to set up Objects and different patterns and whatnot.
Good luck!
Answer by Starx
Here is an illustration
$x = new Thing(); //Instantiate a class
echo $x -> Color(); //call the method