When to use self vs $ this in PHP?

40

I see it as a very frequent question:

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

    
asked by anonymous 18.12.2013 / 12:10

5 answers

51

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

Inheritance

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

  • self::metodo() calls 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();
?>

Result:

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

$this é instância de Animal
self::fala(): Oi
$this->fala(): Oi
    
18.12.2013 / 12:30
4

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

    
18.12.2013 / 12:16
3

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

    
18.12.2013 / 12:13
3

$ 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 eg

self::teste();

or

parent::teste();

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

    
18.12.2013 / 12:17
2

In general, we use $this to maintain encapsulation and avoid collisions of information from one object to another. If for some reason you need to share information with all instances of a class, that's where static variables come in, let's look at 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 using the static variable, it would not be so simple to do this control, see:

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 static variable 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 were finished.

(This example is purely educational!)

    
28.01.2017 / 00:47