How to simplify these variables?

54 views Asked by At
$feed1 = new SimplePie();
$feed2 = new SimplePie();
$feed3 = new SimplePie();
$feed4 = new SimplePie();

$feed1->enable_cache(false);
$feed2->enable_cache(false);
$feed3->enable_cache(false);
$feed4->enable_cache(false);

I tried code below, but I got unexpected result.

$feed1=$feed2=$feed3=$feed4=new SimplePie();
$feed1->$feed2->$feed3->$feed4->enable_cache(false); 
1

There are 1 answers

0
El_Vanja On

You can utilize functions and arrays. Create an array to hold all the instances and make a function that will do all the repetitive work.

function createSimplePies(int $numberOfPies, bool $enableCache): array
{
    $pies = [];
    for ($i = 0; $i < $numberOfPies; $i++) {
        $pie = new SimplePie();
        $pie->enable_cache($enableCache);
        $pies[] = $pie;
    }

    return $pies;
}

$feeds = createSimplePies(4, false);

Then you can easily reference any of the instances through the array index:

$feeds[0]->someMethod(...)