Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable function compatibility with PHP 7 and PHP5

Tags:

php

php-7

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?

like image 625
atwellpub Avatar asked Sep 27 '26 04:09

atwellpub


1 Answers

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
);
like image 144
Narf Avatar answered Sep 28 '26 20:09

Narf