Is it possible to instantiate a class without calling the constructor in PHP?

6

Is it possible to instantiate a class in PHP without the class calling the method __construct ?

Example:

class Test {

     public $chamado = false;

    public function __construct()
    {
          $this->chamado = true;
    }
}


$teste = new Test;

var_dump($teste->chamado); //bool(true);

How to call this class without chamado being changed to true , for example?

Is there a possibility in PHP?

    
asked by anonymous 04.12.2015 / 12:37

2 answers

4

Through the class reflection class ReflectionClass it is possible to do this in php.

Example:

$reflect = new ReflectionClass('Test')

$test = $reflect->newInstanceWithoutConstructor();

var_dump($test->chamado); // bool(false);
    
04.12.2015 / 12:37
2

The constructor method is not required to create an instance of the class, it is done only to set the initial values when creating your instance. This occurs when it invokes the constructor, the constructor can be defined in two ways:

So:

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 destructor method:

class SuaClasse
{
  private $chamado = false;

  public function __destruct()
  {
    //o que será destruído junto à instância
    $this->chamado = true;
  }
} 

You do not necessarily have to create a constructor method of the class in the instance, you also do not 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 constructor, it would look like this:

 $suaClasse = new SuaClasse();
 //será true
 echo $suaClasse->getChamado();

Another way to make the builder work for your need is to define how it 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();
    
04.12.2015 / 12:59