Can an object be instantiated?

Asked

Viewed 182 times

1

I am reading a code and it appears with the following line

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

My question is as follows, if this code is right and what it means because I have never heard that 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();

2 answers

2


Let’s do a demonstration. Note the following code (I imagine 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 we can reach the conclusion that $outraInstancia = new $instancia('Intencional') is the same thing as $outraInstancia = new Objeto('Intencional')

  • True. Corrected.

1

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

My question is as follows, if this code is right and what it means because I have never heard that objects can be instantiated

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

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);
?>

Exit:

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

Reference: The basic Classes and Objects

Browser other questions tagged

You are not signed in. Login or sign up in order to post.