2016-12-29 64 views
0

我正在開發一個與問題詢問有關的程序,所以想象一下Question類。如果我想引用Question中創建Question項目的靜態函數,我可以將此對象賦值給$ this變量嗎?

在更全面的角度

是否有可能改變$ a的值類的這個變量?如果是的話,你怎麼能這樣做?否則,爲什麼我不能將$ this掛鉤到同一類的另一個對象?

+0

你可以根據代碼顯示你正在嘗試什麼,你需要什麼? –

+3

從http://php.net/manual/en/language.oop5.basic.php開始 –

回答

1

所以,我覺得你有點雲裏霧裏什麼$this是。這只是一種參考正在使用的類的實例的方法。該引用僅在該類中發生。

例如:

class Question 
{ 
    function __construct($question, $correctAnswer) 
    { 
     $this->question = $question; 
     $this->correctAnswer = $correctAnswer; 
    } 

    function answerQuestion($answer) 
    { 
     if ($answer == $this->correctAnswer) { 
      return true; 
     } else { 
      return false; 
     } 
    } 
} 

通知,以確定如果答案是正確的,我們比較對所提供的答案:

$this->correctAnswer 

如果我們創建了兩個不同的問題:

$questionOne = new Question("Who is the founder of Microsoft?", "Bill Gates"); 
$questionTwo = new Question("Who is the CEO of Apple, Inc?", "Tim Cook"); 

並提供相同的答案,我們得到不同的結果:

$isCorrect = $questionOne->answerQuestion("Tim Cook"); // FALSE 
$isCorrect = $questionTwo->answerQuestion("Tim Cook"); // TRUE 

這是因爲$this引用了正在使用的實例。

所以,在課堂上,你使用$this。 在課外,您使用對象名稱。在這種情況下:$questionOne$questionTwo

我希望能幫助清理一下。