How do I get rid of the PHP notification 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 Note: Using undefined constant t1 - assumes 't1' in D: \ jobirn \ test \ str.php on line 11

PHP note: using undefined constant t2 is accepted 't2' in D: \ jobirn \ test \ str.php on line 11

How can I get rid of these notifications? 12

0


a source to share


6 answers


You get a notification because PHP does not treat functions as first class objects. When you do

$functions = array(t1, t2);

      

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

When trying to call a string as a function like

$functions[0]()

      

PHP will look for a function with the same name as the string. I would not call this as using a string as a function pointer, it 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 notifications is:

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

      

About why

't1'();

      

does not work? Unfortunately, there is no answer. This is PHP, there are many annoying features. This is the same quirk as:

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

      

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

+7


a source


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

      



Unintuitive, but that it works

+7


a source


The roundtable for this issue is to change php.ini settings from

error_reporting = E_ALL 

      

to

error_reporting = E_ALL & ~E_NOTICE

      

+1


a source


Check the error_reporting () function:

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

It allows you to customize the level of errors, notifications and warnings.

For example, if you want errors and warnings and notifications:

error_reporting (E_ERROR | E_WARNING);

0


a source


Use string declarations if you mean strings:

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

      

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

0


a source


to use strings to call a function you must use curly braces

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

      

edit It seems that {''} () is not working. I remember what it was used for. <

-1


a source







All Articles