Is it possible to define a class within an array in earlier versions of PHP 7?

Asked

Viewed 312 times

4

Is it possible? If so, how? In PHP 7 it is possible to create anonymous classes, which can be defined in any variable/property, but I do not know if it is possible to do this in previous versions, because I am not very active... in PHP.

I want to do something like this:

$arr = array("class" => new class() {});

Then I could build my class this way:

new $arr->class(/* ... */);

P.S: I was thinking about doing this because I’m converting the code from a library, but I didn’t have to do it well necessarily. The situation: the code is written in Javascript and makes use of classes, example:

/**
 * Representa uma tabela em Lua.
 * @param {Object} obj Valores iniciais para montar na nova tabela.
 */
shine.Table = function(obj) {/* ... */};

That would be built like this:

new shine.Table;

The problem of converting this code to PHP is that I don’t find the possibility of implementing a class within an array (or object). The intention is to run Lua in PHP, then adopt Lua in a project, which can be programmed by someone and run to side server.

2 answers

7


Maybe there’s a mix-up in there. If you are talking about PHP versions prior to PHP 7 (currently PHP 5.6 down), there is no feature for Anonymous Classes.

Actually, do not confuse "class instance" with "class statement/definition".

Definition or Declaration is the act of you writing the class. A class instance deals with the object, the use of the class through the operator new.

If the question is in the sense that it is possible to store instances of classes (better known as "object") within a array, yes, it is possible.

Example PHP 5:

class User {
      public $name = 'Wallace';
}

$arr = [];

$arr['user'] = new User;

// OU

$arr = ['user' => new User];

echo $arr['user']->name; // Obtendo o valor

As stated earlier, in versions prior to PHP 7, there are no anonymous classes, so it is not possible to use this feature before PHP 7. But regarding class instances, it is possible to store its values in an index of a array quietly, provided that you can declare it.

Updating

After updating the question, I realized that the author wanted to make a kind of container/reposory with class names.

It is possible to do this in PHP due to the dynamic way the data processing language offers.

Referencing the classes by their name, through a string:

In php it is possible to instantiate a class just knowing its name. If you have a string, for example, with the class name, you can instantiate it.

class TaskClass {
       public function run() {}
}

$repository = [
   'task' => 'TaskClass',
];


$task = new $repository['task'];

$task->run();

Operator resolution of scope combined with ::class

In PHP, in versions prior to 5.5, it is possible to use ::class to resolve a class name.

Behold:

 use App\Project\Task;

 $repository = [

     'task' => \App\Project\Task::class, // nome completo,

     'another_task' => Task::class,
 ];


 $task = new $repository['task'];

 $task2 = new $repository['task'];

 get_class($task); // App\Project\Task(object)

 get_class($task2); // App\Project\Task(object) # esse é o nome real

In some cases, if you need to, you can use the pattern described in this question:

What are the design standards for Serviceprovider and Servicecontainer used in Laravel and Symfony?

Where you use Closures (anonymous functions) to tie the class instantiation logic. Of course, in this case, it is something more complex, but it could be exemplified as follows:

 $repository = [

     'task' => function ($parametro) {
           return new Task($parametro);
      }
 ];


 $task = $repository['task'](); // chama como se faz com as funções
  • 1

    Great answer.

6

The code you posted is instantiating a anonymous class.

Anonymous classes introduced in PHP7.

Regardless of being using array, it will not work in lower versions.

I lower two options, distinct from each other:

Using stdClass

The ultimate goal is unclear, so it might be useful to know that you can instantiate a stdClass

$arr = array("class" => (object)array('foo') = 'bar');

print_r($arr);
// ou
echo $arr['class']->foo;

Class name from a variable

class Foo
{

}

$clss = 'Foo';
$foo = new $clss();

Obviously in this case the class must already exist before being invoked.

  • 1

    Good Daniel, I forgot about stdClass

  • Looks like you didn’t use it stdClass, or am I confused? If I used stdClass it would be purely possible to build $arr->class with new, for example: new $arr->class(...);? I hope I’m not making a mistake.

  • 2

    @Theprohands he used the stdClass yes. When you make a cast (type conversion) in php to object, you turn a array in the stdClass.

  • @Wallacemaxters The difference is that you can define the properties by declaring an array, then converting it to an object. Thank you for your reply

  • 1

    Would you happen to know how to instantiate a class from a variable? For there are indications of this in the question and in this comment.

  • 1

    @Theprohands gave an improved response after your update. Take a look :D

Show 1 more comment

Browser other questions tagged

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