Log in

View Full Version : Function definition oddity, same script or included files.



JasonDFR
04-15-2009, 04:48 PM
If a function is defined in the same file, but after the call to that function, there is no problem.

However if a function is defined in a different file and this file is included after the function call, a fatal error occurs. Fatal error: Call to undefined function func() in..

This is a more academic question than anything, because the best practice to to always define the function prior to calling it.


<?php
// THIS DOESN'T WORK

echo func();

require('func.php'); // includes the func() definition

exit;


<?php
// THIS DOES

echo func();

function func() {

return 'test';

}

exit;

Twey
04-15-2009, 04:59 PM
PHP does the two-pass parse model, to check for functions and load them before actually executing the script. Anything except a basic function definition (includes, conditional definitions, &c.) breaks this, and such functions cannot be preloaded.

JasonDFR
04-15-2009, 05:02 PM
Thanks Twey,

Would you explain the two-pass parse model for me? Whenever you have a minute.

Thanks a lot. Glad you are active here.

Twey
04-15-2009, 08:20 PM
check for functions and load them before actually executing the scriptThere's not much else to say about it, really :)