Why does PHP accept to instantiate a class through a value of a variable, but not of an array?

Asked

Viewed 470 times

0

Why does PHP accept that I create a class through a variable in this way:

$MeuController = 'posts';
$controller = new \app\controllers\admin\$MeuController();

But not like this:

$MeuController[0] = 'posts';
$controller = new \app\controllers\admin\$MeuController[0]();

The real case is that I take the routes through an array in an MVC project, and when I try to create that way I can’t, I have to do so:

$MeuController = $ArrayController[0];

I’m doing something wrong or is it a limitation?

  • 1

    The problem seems to be the namespace, I did a test without it and created the object.

  • Tries the dfinal for good meucontroler(). Thus $this->meucontroller

  • @Victormoral, I’m trying to create a new class, not use an object within an instance, so $this-> wouldn’t be valid in that context.

  • @rray really, I managed to create without namespace. To create with namespace it seems and only in the gambiarra, picking up the line app controllers admin$Meucontroller() and turning into a string already with the value of $Meucontroller concatenated and create the class from the name of that string. Am I doing it wrong or is there another way?

1 answer

1


I’m not sure, but if this doesn’t work it’s probably to avoid complex variables, this can make the php interpreter difficult, so in php7 some things have become more limited, depending on the php7 reference

Syntax of uniform variable

This change brings much greater "orthogonality" to PHP variable operators. It allows for a number of new combinations of operators that were previously not allowed and thus introduces new ways to achieve certain operations.

// nesting ::
$foo::$bar::$baz // Acessa a propriedade $baz de $foo::$bar

// nesting ()
foo()() // Executa o retorno de foo()

// Operadores em expressões incluidas semelhantes ao javascript
(function () {})() // Sintaxe IIFE do JS

The ability to arbitrarily combine variable operators came to reverse the evaluation semantics of the indirect variable, property and method references. The new behavior is more intuitive and always follows an evaluation order from left to right:

                        // maneira antiga         // nova maneira
$$foo['bar']['baz']     ${$foo['bar']['baz']}     ($$foo)['bar']['baz']
$foo->$bar['baz']       $foo->{$bar['baz']}       ($foo->$bar)['baz']
$foo->$bar['baz']()     $foo->{$bar['baz']}()     ($foo->$bar)['baz']()
Foo::$bar['baz']()      Foo::{$bar['baz']}()      (Foo::$bar)['baz']()

Note that the "new way" works in older versions.

Browser other questions tagged

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