2016-12-29 47 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

我希望能帮助清理一下。