SoWizardly
SoWizardly

Reputation: 407

PHP Multiple variable object properties

I'm working with a third-party class, and I need to be able to run a section of code one of two ways, depending...

 $reader->get()->first()->each(function($obj)
 {
    // Do stuff
 }

OR

 $reader->get()->each(function($obj)
 {
    // Do stuff
 }

I've always been able to call properties variably with something like...

 $a = 1;
 $obj->{"$a"}

But unfortunately the below doesn't work...

 if (some scenario)
 {
 $a = "get()->first()";
 }
 else
 {
 $a = "get()";
 }

 $reader->{"$a"}->each(function($obj)

My problem is i'm not sure how to phrase the question for google...I'm assuming there's a solution for the above problem.

Thanks in advance for any help!

Upvotes: 0

Views: 59

Answers (2)

Barmar
Barmar

Reputation: 780842

You can only use ->{$variable} for the names of properties and methods of the class itself, you can't put PHP syntax like -> in there. What you can do is use function variables:

function get_all($reader) {
    return $reader->get();
}
function get_first($reader) {
    return $reader->get()->first();
}

$a = 'get_all'; // or $a = 'get_first';
$a($reader)->each(function($obj) {
    // do stuff
});

Upvotes: 1

Evert
Evert

Reputation: 99523

Alternative to Barmar's answer, which imho is a bit clearer.

$it = function($obj) {
   // do stuff
});

if (some_scenario) {
   $reader->get()->first()->each($it);
} else {
   $reader->get()->each($it);
}

One more solution:

if (some_scenario) {
   $foo = $reader->get()->first();
} else {
   $foo = $reader->get();
}
$foo->each(function($obj) {
    // do stuff
});

Upvotes: 0

Related Questions