How to call a constant as a function name?

In PHP, you can call functions by calling their names inside a variable.

function myfunc(){ echo 'works'; }

$func = 'myfunc';
$func(); // Prints "works"

But you cannot do this with constants.

define('func', 'myfunc');

func(); // Error: function "func" not defined

There are workarounds like these:

$f = func;
$f(); // Prints "works"

call_user_func(func); // Prints "works"

function call($f){ $f(); }
call(func); // Prints "works"

The PHP documentation says: callable

The PHP function is passed by name as a string. You can use any built-in or user-defined function, except for language constructs.

There seems to be nothing about constant values ​​that cannot be called.

I also tried to verify this and, of course,

var_dump(is_callable(func));

prints bool(true).

Now, is there an explanation why this is so? As far as I can see, all workarounds depend on assigning a constant value to a variable, why can't a constant be called?

, , , . , PHP .

+6
4

, /, , (, , ): , https://wiki.php.net/rfc.

+1

PHP 7.0. , , PHP , myfunc func.

<?php
function myfunc(){ echo 'works'; }
define('func', 'myfunc');

(func)();

: https://3v4l.org/fsGmo

PHP , . , PHP

, PHP . PHP , func - .

+1

, :

define('FUNC', 'myFunction');

function myFunction()
{
    echo 'Oh, hello there.';
}

FUNC(); // Fatal error: Call to undefined function FUNC()

PHP FUNC. , : undefined FUNC()

FUNC callable, . , PHP FUNC.

, .

0

Try it. It works for me.

constant('func')();

The function constant()returns a constant value, in your case it is myfunc, then use parentheses ()and you will have a valid call myfunc().

0
source

Source: https://habr.com/ru/post/1533566/


All Articles