Sebastian Sulinski
Sebastian Sulinski

Reputation: 6045

PHP Variable Functions and language constructs

I'm trying to understand why PHP documentation for variable functions states that:

Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

I tried some of these and they work just fine:

function animal() {

    return 'Monkey';

}

$animal = 'animal';

echo $animal();

returns Monkey - just as one would expect.

Same result with print construct - then I tried unset() and it also works absolutely fine:

function getIndex() {

    return 0;

}

$index = 'getIndex';

$array = array(

    'Monkey',
    'Gorilla'

);

unset($array[$index()]);

print_r($array);

this returns Array ( [1] => Gorilla ).

Is there something I'm missing here? Just to add - I'm using PHP 5.5.14.

Upvotes: 1

Views: 170

Answers (2)

Mark Baker
Mark Baker

Reputation: 212402

You're not actually using any language constructs as a variable function:

But try

$function = 'echo'; 
$function('Hello World');

and it won't work, exactly as described in the docs

Use a wrapper function around echo as described in the manual, and then you can use that function as a variable function

function myecho($value) {
    echo $value;
}

$function = 'myecho'; 
$function('Hello World');

Upvotes: 2

Mike S.
Mike S.

Reputation: 2111

They mean another usage:

<?php
$var = "some variable";
$a = "unset"; //also print, isset, echo, include

// you cannot do this:
$a($var);

Of course you can unset or print variable with string containing function name...

(Or am I missing something? :) )

Upvotes: 2

Related Questions