justjoe
justjoe

Reputation: 5564

How PHP translate our code?

I got this code

`

  //
  // prints out "Hello World!"
  //
  hello_world();   //First call

  function hello_world()
  {
    echo "Hello World!<br/>\n";
  }

  hello_world(); //second call

?>`

Both of 'hello_world' call will print out the same result. It's easily to understand why the second call will be output 'Hello world', but how the first call output the same where it's been call before the initiation of the function hello_world itself ?

Upvotes: 1

Views: 97

Answers (3)

xentek
xentek

Reputation: 2645

Functions are evaluated before they are called. Since the function is in the same file, both function calls are valid and point to the function you've defined.

There are exceptions to this, if you've defined a function inside another function, or if you wrap them in conditional statements, but the code you supplied is most perfectly valid.

More Info: http://www.php.net/manual/en/functions.user-defined.php

Upvotes: 1

Kevin
Kevin

Reputation: 13226

PHP functions can be called before they are defined because it is parsed and then executed.

Upvotes: 1

Amber
Amber

Reputation: 526493

PHP files are parsed and then run, in two separate steps. The function is parsed before it is called, which gets rid of the need for forward declarations/prototyping.

Upvotes: 1

Related Questions