Reputation: 157
I have a class called the 'analyst' and he has many 'analysers'. The analysers go looking for certain patterns in a given input.
For now, I create the instances of the 'analysers' in the constructor function of the anaylser like this:
<?php
class analyser {
protected $analysers = array();
public function __construct() {
$analyser1 = new Analyser1();
$this->analysers[] = $analyser1;
$analyser2 = new Analyser1();
$this->analysers[] = $analyser2;
...
}
This works for a limited amount of analysers but I want to create an array ('analyser1', 'analyser2', ...) that will be used in a loop to create all the needed instances. Is this possible or do I need to create every instance manually?
public function __construct() {
foreach ($names as $analyser){
$instance = new $analyser();
$this->analysers[] = $instance;
}
How can i do this ?
Upvotes: 1
Views: 117
Reputation: 14126
This should be straightforward - furthermore you could use nested associative array data to add some initial properties to each object, for example, you might want to give each object a name property:
<?php
class Analyser1
{
protected $name;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$analyserData = [
['name' => 'analyser1'],
['name' => 'analyser2'],
['name' => 'analyser3'],
];
$analysers = [];
foreach ($analyserData as $data) {
$obj = new Analyser1();
$name = $data['name'];
$obj->setName($name);
$analysers[$name] = $obj;
echo 'created ' . $obj->getName() . PHP_EOL;
}
print_r($analysers);
Yields:
created analyser1
created analyser2
created analyser3
Array
(
[analyser1] => Analyser1 Object
(
[name:protected] => analyser1
)
[analyser2] => Analyser1 Object
(
[name:protected] => analyser2
)
[analyser3] => Analyser1 Object
(
[name:protected] => analyser3
)
)
Example here: https://eval.in/133225
Hope this helps! :)
Upvotes: 2
Reputation: 1552
You can use this simple code:
public function __construct() {
for ($i=1; $i<=10; $i++){
// if you want associative array, you should use this part
$key = 'analyser' . $i;
$this->analysers[$key] = new Analyser1();
}
}
And it would create 10 instances of class Analyser1 in array $this->analysers
Upvotes: 1