PHP - force function evaluation?

I am using PHP 5.3, coming from JS and Python, cannot use call () because <PHP 5.4

So let's say I have a function generator, for example. register things in JS land:

function console($meth){
    return function() use($meth) {
        print "<script>console.".$meth.".apply(console,".json_encode(func_get_args()).")</script>";
    };
}

      

I want to dynamically evaluate this, for example:

console($meth)($thing1,$thing2);

      

BUT

//console('log')('hello'); //syntax error!

      

Sad tears! however it works.

$func = console('log');
$func('hello');

      

WHY IS THIS CASE? WHYWHYWHY?

Also, how can I get it to console('log')

evaluate without using eval

or assigning a variable?

+3


source to share


2 answers


This will work as of PHP 5.3:

function console($a) {
    return function($b, $c) {
        echo $b, $c;
    };
}

$f = console("a");
$f("b", "c");

      


If you need to chain the call, this will work for all PHP 5 versions:



class Foo {

    public function call($b, $c) {
        echo $b, $c;
    }
}

function console($a) {
    return new Foo();
}

$f = console("a")->call("b", "c");

      


I would suggest starting learning PHP in the latest version. The PHP developers have added a lot of cool stuff in 5.4 and beyond.

0


source


another solution would be as follows:



    class App_Console {
        private static $methods = array(
            'log',
            'info',
            'warn',
            'dir',
            'time',
            'timeEnd',
            'trace',
            'error',
            'assert'
        );
        function __call($name,$args){
            if(in_array($name,self::$methods)){
                printf("<script>console.$name.apply(console,%s)</script>\n",json_encode($args));
            }
        }
    }

      

0


source







All Articles