I have a question about the "appropriate" use of $ this , self , static and parent in some specific scenarios. I know the meaning and theoretical use of each:
-
$ this : basically references the instance of the object. Serves for non-static properties and methods. Can not be used with constants
- static : same as $ this, but is used for methods, static and constant properties
-
self : used for methods, static and constant properties. In practice in a class hierarchy it references the class in
who's self is being written -
parent : will reference the parent class. It can be used with methods, static and constant properties
In the code below the idea of using parent was to give the visibility that the called method is an "external", or rather, inherited method. Would that be correct?
<?php
class Pessoa{
private $nome;
private $idade;
private $sexo;
protected function setNome($nome)
{
if(is_string($nome)) {
$this->nome = $nome;
return true;
}
return false;
}
protected function setIdade($idade)
{
if(is_int($idade)) {
$this->idade = $idade;
return true;
}
return false;
}
protected function setSexo($sexo)
{
if($sexo == 'M' || $sexo = "F") {
$this->sexo = $sexo;
return true;
}
return false;
}
public function getNome()
{
return $this->nome;
}
public function getIdade()
{
return $this->idade;
}
public function getSexo()
{
return $this->sexo;
}
}
class Funcionario extends Pessoa
{
private $empresa;
private $salario;
public function __construct($nome, $idade, $sexo, $empresa, $salario)
{
parent::setNome($nome);
parent::setIdade($idade);
parent::setSexo($sexo);
$this->empresa = $empresa;
$this->salario = $salario;
}
public function getEmpresa()
{
return $this->empresa;
}
public function getSalario()
{
return $this->salario;
}
}
$funcionario = new Funcionario("Yuri", "19", "Masculino", "Tam", "3000");
echo $funcionario->getNome() . ' Trabalha na: ' . $funcionario->getEmpresa() . ' e ganha ' . $funcionario->getSalario();
Now a macro question: Is there a recipe that suggests when it's best to use $ this , self , static / strong>?