Joe
Joe

Reputation: 3834

Calling a method of an instance of a class

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?

Upvotes: 1

Views: 104

Answers (4)

Paolo Falabella
Paolo Falabella

Reputation: 25844

it's $x-> Color();. PHP uses -> instead of the dot (like in other languages) to call instance methods. Also your code does not look like PHP.

Thing x = new Thing(); should be something like $x=new Thing();

public string Color() { should look like public function Color() {

Upvotes: 1

Jemaclus
Jemaclus

Reputation: 2376

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!

Upvotes: 4

Mike Purcell
Mike Purcell

Reputation: 19979

Try this:

$thing = new Thing();

echo $thing->Color();

Upvotes: 2

Starx
Starx

Reputation: 78971

Here is an illustration

$x = new Thing(); //Instantiate a class

echo $x -> Color(); //call the method 

Upvotes: 1

Related Questions