Can an object be instantiated?

1

I'm reading a code and it consists of the following line

$this->controlador = new HomeController();
$this->controlador = new $this->controlador( $this->parametros )

My question is as follows, if this code is true and what it means because I had never heard of which objects can be instantiated

class HomeController extends MainController
{

 /**
 * Carrega a página "/views/home/home-view.php"
 */
    public function index() {
 // Título da página
 $this->title = 'Home';

 // Parametros da função
 $parametros = ( func_num_args() >= 1 ) ? func_get_arg(0) : array();
    
asked by anonymous 21.12.2017 / 20:08

2 answers

2

Let's do a demonstration. Note the following code (I guess it does the same thing as the example shown in the question):

<?php
class Objeto{
    private $atributo = 'Um simples atributo';
    public $parametro = '';
    public function __construct($parametro = 'Automatico'){
        $this->parametro = 'Uma função qualquer chamada por ' . $parametro;     
    }
}

$instancia = new Objeto();
$outraInstancia = new $instancia('Intencional');

var_dump($instancia);
var_dump($outraInstancia);

var_dump($instancia->parametro);
var_dump($outraInstancia->parametro);

This code generates the following output:

/a.php:13:
object(Objeto)[1]
  private 'atributo' => string 'Um simples atributo' (length=19)
  public 'parametro' => string 'Uma função qualquer chamada por Automatico' (length=44)

/a.php:14:
object(Objeto)[2]
  private 'atributo' => string 'Um simples atributo' (length=19)
  public 'parametro' => string 'Uma função qualquer chamada por Intencional' (length=45)

/a.php:16:string 'Uma função qualquer chamada por Automatico' (length=44)

/a.php:17:string 'Uma função qualquer chamada por Intencional' (length=45)

With this you can conclude that $outraInstancia = new $instancia('Intencional') is the same as $outraInstancia = new Objeto('Intencional')

    
21.12.2017 / 23:40
1

A new feature has been introduced in PHP 5.3 that an instance of an object can be created.

  

My question is, if this code is right and what it means because I had never heard of which objects can be instantiated

Yes it is correct, but, the version that functional such resource is PHP 5.3, ie before could not instantiate this way, but, from that version was introduced as a new feature.

Example of the site itself www.php.com

<?php
class Test
{
    static public function getNew()
    {
        return new static;
    }
}

class Child extends Test
{}

$obj1 = new Test();
$obj2 = new $obj1;
var_dump($obj1 !== $obj2);

$obj3 = Test::getNew();
var_dump($obj3 instanceof Test);

$obj4 = Child::getNew();
var_dump($obj4 instanceof Child);
?>

Output:

bool(true)
bool(true)
bool(true)

Reference The Basic Classes and Objects

    
23.12.2017 / 23:42