Question

function t1()
{
  echo 1;
}
function t2()
{ 
  echo 2;
}

$funcs = array(t1,t2);

$length = count($funcs);
for($i=0;$i<$length;$i++)
{
$funcs[$i]();
}

when I execute this tiny php file:

PHP Notice: Use of undefined constant t1 - assumed 't1' in D:\jobirn\test\str.php on line 11

PHP Notice: Use of undefined constant t2 - assumed 't2' in D:\jobirn\test\str.php on line 11

How can I get rid of those Notices? 12

Was it helpful?

Solution

You get a notice because PHP doesn't treat functions as first class objects. When you do this

$functions = array(t1, t2);

The PHP engine sees t1, and t2, and tries to resolve it as a constant, but because it cannot find a constant named t1/t2, it "assumes" that you wanted to type array('t1', 't2'); If you do a var_dump($functions), you can see that the items in the array are strings.

When you try to call a string as a function, like

$functions[0]()

PHP will look for a function with the same name as the string. I wouldn't call this as using a string as a function pointer, this is more like using reflection. PHP calls it "variable functions", see:

http://hu2.php.net/manual/en/functions.variable-functions.php

So, the correct way to get rid of the notices is:

$functions = array('t1', 't2');

About why does

't1'();

not work? Unfortunately there is no answer. It's PHP, there are a good number of these annoying as hell quirks. It's the same quirk as:

explode(':', 'one:two:three')[0];
Parse error: syntax error, unexpected '[' in php shell code on line 1

Edit:
The above mentioned array referencing syntax is available in PHP5.4, it's called array dereferencing.

OTHER TIPS

$funcs = array('t1','t2');

Unintuitive, but that's how it works

The work-round to this issue is to change the php.ini settings from

error_reporting = E_ALL 

to

error_reporting = E_ALL & ~E_NOTICE

Check out the error_reporting() function:

http://us2.php.net/manual/en/function.error-reporting.php

It lets you configure what level of errors, notices and warnings are displayed.

For example, if you want errors and warnings and no notices:

error_reporting(E_ERROR | E_WARNING);

Use string declarations if you mean strings:

$funcs = array('t1','t2');

See also the chapter on varaible functions in the PHP manual.

to use strings to call a function, you should use curly braces

'hello'() // wont work
$hello = 'hello'; $hello() // will work

edit it seems {''}() doesnt work. i remember it used to >.<

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top