Search code examples
phpnotice

how to get rid of PHP notice here?


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


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.