There may be confusions of terms there. If you are talking about PHP versions prior to PHP 7 (currently PHP 5.6 down), there is no Anonymous Class resource.
In fact, do not confuse "class instance" with "class declaration / definition".
Definition or Statement is the act of writing the class to you. The class instance deals with the object, using the class with the new
operator.
If the question is that it is possible to save instances of classes (better known as "object") within a array
, yes, it is possible.
PHP 5 example:
class User {
public $name = 'Wallace';
}
$arr = [];
$arr['user'] = new User;
// OU
$arr = ['user' => new User];
echo $arr['user']->name; // Obtendo o valor
As mentioned earlier, in versions prior to PHP 7, there are no anonymous classes, so you can not use this feature before PHP 7. But in relation to class instances, you can save your values to an index of one array
quietly, since you can declare it.
Update
After updating the question, I realized that the Author wanted to make a kind of container / repostory with class names.
You can do this in PHP because of the dynamic way the language treats the data.
Referencing classes by their name, using a string
:
In php it is possible to instantiate a class only by knowing its name. If you have a string, for example, with the name of the class, you can instantiate it.
class TaskClass {
public function run() {}
}
$repository = [
'task' => 'TaskClass',
];
$task = new $repository['task'];
$task->run();
Scope resolution operator combined with ::class
In PHP, in versions prior to 5.5, you can use ::class
to resolve the name of a class.
See:
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 ServiceProvider and ServiceContainer design patterns used in Laravel and Symfony?
Where you use Closures
(anonymous functions) to tie the instantiation logic of the class. 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