3

Well I confused by behavior of PHP when parsing a PHP file. I am reading this since long that

The PHP language is interpreted

So I have code

var_dump(function_exists('abc')); exit;
function abc() {
    return;
}

var_dump should print false as per my assumption but it print bool(true).

Can somebody please help me to understand this behavior?

Sumit
  • 1,619
  • 1
  • 11
  • 24
  • it's pre-compiled before running, not interpreted while running AFAIK – RST Jan 07 '16 at 08:00
  • @RST Any ref or link for that ? – Sumit Jan 07 '16 at 08:02
  • function abc() was called before exit; (using function_exists) that's why it returns 'true'. Even if you define the function after exit and it is called before exit, it still execute. – Ren Camp Jan 07 '16 at 08:02
  • what I meant was, using function_exists(), the function abc() was called because it searched if that certain function exists. – Ren Camp Jan 07 '16 at 08:04
  • @RenCamp I know the same is happening that what you told but any link for this behavior ? Or where it has been written ? – Sumit Jan 07 '16 at 08:05
  • [Reference](http://laruence-wordpress.stor.sinaapp.com/uploads/the-php-life-cycle.pdf) – Mark Baker Jan 07 '16 at 08:07
  • reference: http://php.net/manual/en/function.function-exists.php. It states that "Checks the list of defined functions, both built-in (internal) and user-defined, for function_name" – Ren Camp Jan 07 '16 at 08:08
  • @RenCamp - `function_exists()` will not call function `abc()` at all, it simply checks if there is a definition for function `abc()` in the global functions list – Mark Baker Jan 07 '16 at 08:08
  • just what @RST said, it's pre-compiled – Ren Camp Jan 07 '16 at 08:09
  • @MarkBaker, my bad. it's checked, not called. – Ren Camp Jan 07 '16 at 08:10
  • 2
    What you see here is often called "function hoisting". Non-conditional definitions of functions are "hoisted" to the top of the script. – NikiC Jan 08 '16 at 14:12
  • @NikiC Thanks but you should have added this as answer. – Sumit Jan 09 '16 at 05:33

2 Answers2

2

See this answer.

In short, it is compiled into a type of bytecode at runtime and then interpreted - in doing this, you will have the definitions for your functions available, even if they appear at the very end.

Community
  • 1
  • 1
Matt Clark
  • 27,671
  • 19
  • 68
  • 123
0

function_exist will Checks the list of defined functions, both built-in (internal) and user-defined, for function_name. So, php interpreter checks if the function with the name is defined in the bytecode which is complied before interpreted.

Drudge Rajen
  • 7,584
  • 4
  • 23
  • 43