The constructor method is not required to create an instance of the class, it is only done to set the initial values when creating its instance. This occurs when it invokes the constructor, the constructor can be defined in two ways:
Thus:
class SuaClasse
{
private $chamado = false;
public function __construct()
{
//o que será construído junto à instância
$this->chamado = true;
}
public function setChamado($boolean)
{
$this->chamado = $boolean;
return $this;
}
public function getChamado()
{
return $this->chamado;
}
}
or so:
class SuaClasse
{
private $chamado = false;
public function SuaClasse()
{
//o que será construído junto à instância
$this->chamado = true;
}
public function getChamado()
{
return $this->chamado;
}
}
There is also the destructive method:
class SuaClasse
{
private $chamado = false;
public function __destruct()
{
//o que será destruído junto à instância
$this->chamado = true;
}
}
You don’t necessarily need to create a class constructor method in the instance, you also don’t have to worry about the constructor method setting its output:
$suaClasse = new SuaClasse;
You can set the values:
//será false
$suaClasse->setChamado(false);
echo $suaClasse->getChamado();
//será true
$suaClasse->setChamado(true);
echo $suaClasse->getChamado();
Directly, to call the builder, would be so:
$suaClasse = new SuaClasse();
//será true
echo $suaClasse->getChamado();
Another way to make the builder work for his needs is to define how he will start:
class SuaClasse
{
private $chamado = false;
public function __construct($boolean)
{
//o que será construído junto à instância
$this->chamado = $boolean;
}
public function getChamado()
{
return $this->chamado;
}
}
$suaClasse = new SuaClasse(true);
//será true
$suaClasse->getChamado();
$suaClasse = new SuaClasse(false);
//será false
$suaClasse->getChamado();
Yes it is possible, believe me!
– rray
It would be simpler if you didn’t define a method
construct
.– Edilson
That’s what Ivan said. I also agree. But anyway, it’s worth the curiosity ;)
– Wallace Maxters
If you think the title has gone bad do the rollback please.
– Guilherme Nascimento
The method you have specified below will cause some problems for some people who do not understand the use of constructors, it would be good if you explained a reason and when to do this.
– Edilson