Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a constant as a function name?

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

function myfunc(){ echo 'works'; }

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

But, you can't 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 on callable says:

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs.

There seems to be nothing about constant values not being callable.

I also tried to check it, and of course,

var_dump(is_callable(func));

prints bool(true).

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

And again, just to make it super clear, I don't need a way to call the function, I even presented some there. I want to know why PHP doesn't allow calling the function directly through the constant.

like image 205
PurkkaKoodari Avatar asked Mar 26 '14 15:03

PurkkaKoodari


People also ask

How do you define a constant?

A constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant. When associated with an identifier, a constant is said to be “named,” although the terms “constant” and “named constant” are often used interchangeably.


1 Answers

This works since PHP 7.0. The only things is that you have to use more expressive syntax, so that PHP knows you mean to execute myfunc instead of func.

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

(func)();

Try this online: https://3v4l.org/fsGmo

The problem with PHP is that constants and identifiers are expressed as the same thing in the tokenizer. See online how this syntax is tokenized by PHP

When you use parentheses to change precedence of operations on the constant, you tell PHP to first parse the constant and use its value to execute the function. Otherwise PHP will think that func is the name of your function.

like image 149
Dharman Avatar answered Sep 28 '22 19:09

Dharman