9

The following code runs in PHP

<?php

$foo = "Chocolate milkshake";

go($foo);

function go($param) {
    echo $param;
}

?>

// Output: chocolate milkshake

See this Demo http://codepad.viper-7.com/ToApZa

This code runs without errors and prints specified output, why? I thought this "function hoisting" only occurred in JavaScript

Dharman
  • 30,962
  • 25
  • 85
  • 135
Michael Coleman
  • 3,288
  • 3
  • 19
  • 18
  • 5
    PHP isn't interpreted line-wise. The parser does prepare a function declaration table. They need to be declared in a scripts outermost global code block though. Deferred and nested functions aren't picked up as such. – mario Nov 30 '14 at 08:15
  • I wondered if that was the case - made a little test [here](http://codepad.viper-7.com/8pqSgG) - thanks – Michael Coleman Nov 30 '14 at 08:22

1 Answers1

7

It doesn't matter where you declare your functions in PHP in most cases, as you've just proved :)

Take a look at this page for more details. The key point:

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

Ben
  • 1,571
  • 1
  • 13
  • 29