When to use self vs $this in PHP?

Asked

Viewed 28,367 times

47

I see it as a very frequent doubt:

When should we use the self::, or the $this in PHP. Which form is best suited for use and what is the difference between the 2 situations?

5 answers

64


In a simplified form, $this refers to the current object (instance), and self refers to the class. Therefore, as a general rule, $this to access members (attributes, methods) of the instance and self to access static members.

Inheritance

When using inheritance, however, there is difference between using self and $this when calling an instance method:

  • self::metodo() calls the metodo() of current class;
  • $this->metodo() calls the metodo() of the class used to instantiate the object being executed (which may be a subclass of the class where the call is made). You can find out what class this is using get_class($this).

Example:

<?php
class Animal {
  public function teste() {
    echo "\$this é instância de " . get_class($this) . "\n";

    // chama Animal::fala(), independentemente do
    // tipo da instância
    echo "self::fala(): ";
    self::fala();

    // chama fala() na classe usada pra instanciar
    // este objeto
    echo "\$this->fala(): ";
    $this->fala();
  }
  public function fala() {
    echo "Oi\n";
  }
}

class Gato extends Animal {
  public function fala() {
    echo "Miau\n";
  }
}

// Nesse caso, self != get_class($this)
// - self == Animal
// - get_class($this) == Gato
$gato = new Gato();
$gato->teste();

echo "\n";

// Nesse caso, self == get_class($this) == Animal
$animal = new Animal();
$animal->teste();
?>

Upshot:

$this é instância de Gato
self::fala(): Oi
$this->fala(): Miau

$this é instância de Animal
self::fala(): Oi
$this->fala(): Oi
  • Good answer. Very explanatory.

  • 6

    Interesting fact: the operator of resolution of scope "::" is called Paamayim Nekudotayim.

  • In cases where you can use both the self:: and the $this, use the self:: that uses less memory!

5

The difference is that the self is for when the class (or instance), is in a static context (whether a method or property), and obviously this is when it is not static.

3

In general, we use the $this to maintain encapsulation and avoid collisions of information from one object into the other. If for some reason you need to share information with all instances of a class, this is where the Static variables come in, let’s take an example:

<?php

class Notebook
{
    private static $quantidadeDisponivel = 5;

    public function getQuantidadeDisponivel()
    {
        return self::$quantidadeDisponivel;
    }

    public function comprar()
    {
        /**
         * Realiza o processo de compra do notebook e atualiza quantidade disponivel
         */
        self::$quantidadeDisponivel--;
    }
}

$carrinhoJoao = new Notebook;
$carrinhoJoao->comprar();
$notebooksRestantes =  $carrinhoJoao->getQuantidadeDisponivel(); 
print $notebooksRestantes; // imprime 4

$carrinhoPedro = new Notebook;
$carrinhoPedro->comprar();
$notebooksRestantes =  $carrinhoPedro->getQuantidadeDisponivel(); 
print $notebooksRestantes; // imprime 3

$carrinhoPaulo = new Notebook;
$carrinhoPaulo->comprar();
$notebooksRestantes =  $carrinhoPaulo->getQuantidadeDisponivel(); 
print $notebooksRestantes; // imprime 2

$carrinhoJoao->comprar();
$notebooksRestantes =  $carrinhoJoao->getQuantidadeDisponivel(); 
print $notebooksRestantes; // imprime 1

$carrinhoPedro->comprar();
$notebooksRestantes =  $carrinhoPedro->getQuantidadeDisponivel(); 
print $notebooksRestantes; // imprime 0

Without the use of the variable Statica, it would not be so simple to make this control, see only:

class Desktop
{
    private $quantidadeDisponivel = 5;

    public function getQuantidadeDisponivel()
    {
        return $this->quantidadeDisponivel;
    }

    public function comprar()
    {
        /**
         * Realiza o processo de compra do notebook e atualiza a quantidade disponível
         */
        $this->quantidadeDisponivel--;
    }
}



$carrinhoJoao = new Desktop;
$carrinhoJoao->comprar();
$notebooksRestantes =  $carrinhoJoao->getQuantidadeDisponivel(); 
print $notebooksRestantes; // imprime 4

$carrinhoPedro = new Desktop;
$carrinhoPedro->comprar();
$notebooksRestantes =  $carrinhoPedro->getQuantidadeDisponivel(); 
print $notebooksRestantes; // imprime 4

$carrinhoPaulo = new Desktop;
$carrinhoPaulo->comprar();
$notebooksRestantes =  $carrinhoPaulo->getQuantidadeDisponivel(); 
print $notebooksRestantes; // imprime 4

As we have seen, with the use of the variable Statica we had the result 4,3,2,1,0 and with the common variable we had 4.4.4, the computers would continue to be sold even though they had already run out.

(This example is merely educational!)

3

$this is used within the class to access object properties/methods. self is used to access static members.

3

The $this points to the object and the self points to the class itself.

The self can also be used when the class extends another and you want to access the implementation of it or its relative for example

self::teste();

or

parent::teste();

But usually the self will be used to access static class data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.