What is the meaning of $ this

I saw that some scripts contain $thisin PHP a script that has OOP, I never knew its meaning ... for example

$this->refresh();

Perhaps explain to me what it means $this...?

But I know that you cannot use it as a dynamic variable of a type $this_is_a_variable, but why cannot it be used as a dynamic variable?

+2
source share
4 answers

$this is a reference to the current object.

It can only be used in classes.

From manual:

$this , . $ ( , , , , , ).

:

class Classname
 {
   public $message = "The big brown fox... jumped....";

   function showMessage()
    {
      echo $this->message; // Will output whatever value 
                           // the object message variable was set to
    }
  }

$my_object = new Classname();  // this is a valid object
$my_object->name = "Hello World!";
$my_object->showMessage();  // Will output "Hello world"

$this :

Classname::showMessage(); // Will throw an error: 
                          // `$this` used while not in object context
+18

, . :

class CFoo
  {
  private $var;
  public function setFoo($fooVal)
    {
    $this->var = $fooVal;
    }
  }

$ .

+4

PHP *. $this.

** " ", . . *

:

class Car
{
    private $make;

    public function setMake($make)
    {
         $this->make = $make;
    }

    public function setModel($model)
    {
         $this->model = $model;
    }

    public function whatCar()
    {
        return "This car is a " . $this->make . " " . $this->model;
    }
}

:

$car = new Car();

$car->setMake('Ford');
$car->setModel('Escort');

echo $car->whatCar();
//This car is a Ford Escort
+3

$ this refers to the current class object. $ this is used in methods that are members of a particular class. Therefore, inside these methods, the method already has information about a specific "instance" of this class. Thus, $ this can be used directly to refer to the current object, and not to get and assign the object to another variable.

0
source

Source: https://habr.com/ru/post/1766168/


All Articles