|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-09-24 19:56 UTC] herb at bobbingwide dot com
Description:
------------
When enclosing code between if ( expression ) { and } it appears that versions
of PHP up to and including 5.3.17 require functions to be declared before they
are used. I first noticed the problem when I tried to wrap a whole PHP source
file like this
<?php
if ( !defined( 'CONSTANT' )) {
define( 'CONSTANT', true );
// whole file here
} // end defined
I reduced the problem to the simplest; replacing !defined( 'CONSTANT') with true
and got the same unexpected results. The code did not work unless the (top
level) functions were declared before they were used.
I found the problem on PHP 5.3.5 where the code produced a Fatal error: Call to
undefined function. I have since reproduced the Fatal error on PHP 5.3.16 and
5.3.17
If you remove the 'if test' (lines 2 and 7) the code works fine.
If you put the call to the function after the declaration that also works.
This code, where the call to b() is before the declaration of function b, also
works
<?php
if ( true ) {
function a() {
echo "a" . PHP_EOL;
b();
}
function b() {
echo "b" . PHP_EOL;
}
a();
}
producing
a
b
Test script:
---------------
<?php
if ( true ) {
a();
function a() {
echo "a" . PHP_EOL;
}
}
Expected result:
----------------
a
Actual result:
--------------
Fatal error: Call to undefined function a() in C:\apache\htdocs\wordpress\wp-con
tent\plugins\play\defined.php on line 3
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 02 05:00:01 2025 UTC |
Top level declaration are available after compiling, but conditional declaration can only be available after executed. (since PHP itself didn't do optimization, i`f(true) {doSomething();}` is not equal to `doSomething();` exactly ) the same rules for class declarations. This could be classified as a documentation problem.hmm, it's not the only way, since you can get it works well by declare it before reference to it: <?php if ( true ) { function a() { echo "a" . PHP_EOL; } a(); }@nicic thanks for the link to the documentation. I hadn't realised I could use return... having previously failed to get a working solution with exit :-) I'll most likely change my code to something like this. <?php if ( defined( 'CONSTANT' )) return; define( 'CONSTANT', true ); a(); function a() { echo "a" . PHP_EOL; } Then I don't have to worry about the final } at the end of the file So should #17055 be marked as Closed now, rather than Suspended?