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
Great answer.
– taiar