S
S
snake22021-09-24 22:58:12
PHP
snake2, 2021-09-24 22:58:12

How to create a certain number of objects?

Let's say there are 2 classes

class Apple
{
}

class Orange
{
}


What is the best way to create 10 instances of the Apple class and 20 instances of the Orange class without using loops and something like:
new Apple()
new Apple()
new Apple()
new Apple()

Maybe there is some pattern?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2021-09-24
@snake2

Somehow fake the loop with, say, arrays?

$length = 10;
array_map(fn() => new Apple(), array_fill(0, $length, NULL));

Well, arrange a fake factory
function makeMany(string $className, int $quantity)
{
    return array_map(fn() => new $className(), array_fill(0, $quantity, NULL));
}

// использование
makeMany("Apple", 10);
makeMany("Orange", 20);

// или
makeMany(Apple::class, 10);
makeMany(Orange::class, 20);

G
gazievDima, 2021-09-26
@gazievDima

Factory pattern, read about it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question