0

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!

0

2 Answers 2

1

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
});
Sign up to request clarification or add additional context in comments.

Comments

0

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.