Using $ this in POO PHP [duplicate]

1

I do not quite understand what the $ this "catches".

In case we have a code like this, for example:

<?php
class Teste {
    public $testando;
    public function VamosTestar(){
       this->$testando = false; 
   }
}

In the case there, $ this is "replacing" what? A test class? If I do this, will it be the same thing?

<?php
    class Teste {
        public $testando;
        public function VamosTestar(){
           Teste->testando = false; 
       }
    }

In case, I think not, put in my NetBeans returned me an error. But what would I use if I did not want to use $ this?

    
asked by anonymous 09.06.2017 / 21:22

2 answers

3
  

Use $this to reference the object itself. Another option would be self , but this references the class itself. Simply put, $this->variavel is for non-static methods, self::variavel is for static members.

An example of $ this and self usage.

class Foo {
    // Variável privada
    private $bar = 1;

    // Variável estática
    private static $fooBar = 2;

    function __construct() {
        // Imprime ambas variáveis
        echo $this->bar . ' ' . self::$fooBar;
    }

    // Caso tente imprimir $bar com self, receberá uma mensagem de erro
    // Caso tente imprimir $fooBar com this, receberá uma mensagem de erro
}
    
09.06.2017 / 21:31
2

Basically, this refers to the class itself.

Understand as follows:

class Teste {
    public $testando;
    public function VamosTestar(){
       $this->testando = false; 
       //estaClasse->testando ou Teste->testando
   }
}

$this : "This class"

testando attribute with name testing.

To access functions of the class itself or attributes of the class itself we use the word $this , $this can also be used to access functions and attributes inherited from another class as in the example below:

class Pai {
    public $nome;
}

class Filho extends Pai {
    public function foo(){
        return $this->nome;
    }
}

Usage:

$filho = new Filho();
$filho->foo();

$this will search the $nome attribute from the first extended class to the current class.;

    
09.06.2017 / 21:32