2012-03-02 75 views
1

原諒我問這樣一個新手問題,但我無法弄清楚如何在PHP中調用方法。這裏就是我想要做的(僞代碼):調用一個類的實例的方法

class Thing { 
    public string Color() { 
     return "taupe"; 
    } 
} 

Thing x = new Thing(); 
echo x.Color(); 

這應該呼應taupe作爲其結果。我卡住的部分是最後一行:調用Color方法x。在PHP中如何做到這一點?

+0

試試這個:x-> Color(); – 2012-03-02 18:44:11

回答

4

在PHP中,你會怎麼做SOMET興象:

class Thing { 
    public function color() { 
     return "taupe"; 
    } 
} 

$thing = new Thing; 
echo $thing->color(); 

你接近:)

我建議在PHP's OOP information here讀了。他們有很多關於如何設置對象和不同模式以及什麼的很好的信息。

祝你好運!

1

它是$x-> Color();。 PHP使用 - >而不是點(與其他語言一樣)來調用實例方法。 另外你的代碼看起來不像PHP。

Thing x = new Thing();應該像$x=new Thing();

public string Color() {應該像public function Color() {

1

這裏有一個例子

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

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

試試這個:

$thing = new Thing(); 

echo $thing->Color(); 
相關問題