user3808307
user3808307

Reputation: 1549

Can I generate instances of a class inside a for loop in PHP?

I want to generate a class instance for each post value.

Something like this

$i=0;

foreach ($_POST['URL'] as $url) {
    $classInstance.$i = new className();
    $i++;
}

Each with a different name.

I read about variable variable names like:

${"classInstance" . $i} = new className(); 

But it's been previously discouraged in other questions (PHP Variables - Concatenate variable name)

Is there any other way to achieve the same without using variable variable names?

Upvotes: 0

Views: 68

Answers (1)

hasumedic
hasumedic

Reputation: 2167

The way you're proposing is perfectly valid. But there are not many justified use cases for using that piece of functionality for simply concatenating numbers to variables. If you need a collection of variables, simply aggregate those objects into a data structure such as an array or an SPL List, and manipulate them from there.

Upvotes: 1

Related Questions