3

I have a situation where this works in PHP5 but fatals in PHP7:

/* load batch processing data into variable */
$args = get_option('leads_batch_processing');
/* process batches */
self::$args['method']($args);

And this works in PHP7 but fatals PHP5:

/* load batch processing data into variable */
$args = get_option('leads_batch_processing');
/* process batches */
 self::{$args['method']}($args);

How can I use the variable function successfully in both PHP environments? I tried using an if condition based on PHP version but the PHP7 version's syntax fatals PHP5 so I cannot go that route.

What do I do?

4
  • call_user_func()? Commented Mar 26, 2016 at 19:56
  • Could you propose it as an answer? In the case above $args is not a private or static variable. But inside $args['method'] there is a function name that exists within the calling class (self::) Commented Mar 26, 2016 at 20:11
  • The second code should work on both PHP 5 and PHP 7. Make sure you're not testing on some outdated PHP version (like 5.3). Commented Mar 26, 2016 at 20:39
  • I can't afford that context working as a WordPress plugin developer I will see PHP version from 5.3 to 7. The second version will fatal on a lower version of PHP. It doesn't like the brackets. Commented Mar 26, 2016 at 21:15

1 Answer 1

2

Assign it to a regular variable, which wouldn't cause a syntax error:

$method = $args['method'];
$this->$method($args);

Or, similarly to what was suggested in the comments, use call_user_func():

call_user_func(
    array($this, $args['method']),
    $args
);
Sign up to request clarification or add additional context in comments.

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.