0

I'm developing a program that has to do with Question asking, so imagine there's the Question class. If I wanted to refer to a static function in Question which creates a Question item could I assign this object to $this variable?

In a more general perspective

Is it possible to change the value of $this variable of a class? If yes, how can you do that? Otherwise why can't I hook $this to another object of same class?

Mehul Kuriya
  • 608
  • 5
  • 18
catchiecop
  • 388
  • 6
  • 24

2 Answers2

2

The pseudo-variable $this is a reference to the calling object. Trying to re-assign it will generate a fatal error.


PHP manual: http://php.net/manual/en/language.oop5.basic.php

Similar question: PHP Fatal error: Cannot re-assign $this

Community
  • 1
  • 1
1

So, I think you are a little foggy on what $this is for. It is simply a way to refer to the instance of the class that is being utilized. This reference only occurs within the class.

For example:

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

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

Notice to determine if the answer is correct we compare the provided answer against:

$this->correctAnswer

If we create two different questions:

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

And provide the same answer, we get different results:

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

This is because $this refers to the instance being used.

So, within the class, you use $this. Outside the class, you use the object name. In this case: $questionOne or $questionTwo

I hope that helps clear things up.

BizzyBob
  • 12,309
  • 4
  • 27
  • 51