6
I have a question about the "proper" use of $this, self, Static and Parent in some specific scenarios. I know the meaning and theoretical use of each:
$this: basically references the object instance. Serves for nonstatic properties and methods. Cannot be used with constant
Static: same as $this, but is used for methods, static and constant properties
self: used for methods, static properties and constants. In practice in a class hierarchy it references the class in
who self is being writtenParent: reference parent class. Can be used with methods, static properties and constants
In the code below the idea of using Parent was to give the visibility that the so-called method is an "external" or rather inherited method. This would 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 any recipe that suggests when it is best to use $this, self, Static or Parent?
Beyond what is already written in the question? No.
– Maniero
Related: What is the difference between Static::Property, Classname::property, self:?, What’s the difference between Static and self in PHP?
– Woss