Abs
Abs

Reputation: 57916

Includes and Functions calls

I just want to confirm something as my understanding has been shaken by a test I did on another server that I expected something to work and it didn't. Please see question in code below.

<?php

function xyz(){
} 

include("test.php");
/*
* A function in the above include checks if the function abc function_exists(). 
* Will it return a true? What about for xyz?
*/

function abc(){
}

?>

Thanks all

Upvotes: 1

Views: 102

Answers (5)

NullUserException
NullUserException

Reputation: 85458

You can think of includes as copying and pasting the whole file into where the include statement is.
So really, you are looking at:

function xyz(){
} 

var_dump(function_exists('xyz'));
var_dump(function_exists('abc'));

function abc(){
}

Which both return true, as demonstrated here (ie: functions defined in a script are accessible at any point1).

1 See nikic's answer for exceptions to this.

Upvotes: 3

NikiC
NikiC

Reputation: 101926

In PHP a function doesn't need to be declared before it is used or referenced. There is only one exception to this: If the function is defined conditionally (in an if statement) the function is available only after the if statement was executed. (But this is logical because PHP can't know whether the if will or will not evaluate.)

See the manual:

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

Upvotes: 2

Alin P.
Alin P.

Reputation: 44346

It looks like a function is found as existing even if it's declared after the check code.

<?php

echo function_exists('abc').PHP_EOL;
echo function_exists('xyz').PHP_EOL;

function xyz(){
} 

function abc(){
}

?>

I don't know why this happens but it may be because PHP code is compiled into an internal format before running it. So all functions will be created after compiling and before running.

Regards, Alin

Upvotes: 0

Cedric
Cedric

Reputation: 5303

abc exists wherever I check about its existence. It is probably due to the fact that PHP engine may parse the code and create all the functions first before doint anything else : it probably read all the lines with "function foobar()" , and then execute the rest of the code

Upvotes: 0

Alec
Alec

Reputation: 9078

The script is parsed from top to bottom. So when test.php is included, xyz will exist, but abc won't. Whups, I was thinking about something else, but NullUserException is right. All the functions that are on the loaded page will exists according to function_exists().

Upvotes: 0

Related Questions