7

If PHP is interpreted language(every line is executed as it is reached), how come it throws errors if the error occurs inside a function which is never executed?

Or may be I don't get what interpreted means?

For e.g

<?php 

$number = 1;

function square(){

 $foo = 1  //missing semicolon, throws error

}
echo $number;

?>
Sam Becker
  • 19,231
  • 14
  • 60
  • 80

3 Answers3

7

Because its syntax is first parsed in an attempt to tokenize it, before the PHP interpreter can begin.

alex
  • 479,566
  • 201
  • 878
  • 984
4

Before the page is actually interpreted by PHP, it is run through a preprocessor. That picks up any errors in your page before it actually starts to run and preforms a whole bunch of other operations to prepare your script for interpretation.

This ensures the scripts syntax is correct before anything happens and is why PHP throws an error even through your function is never called.

Sam Becker
  • 19,231
  • 14
  • 60
  • 80
  • does the preprocessor converts code into some kind of byte code or something ? –  May 31 '11 at 05:49
  • I'm not sure on the specifics, but there is an interesting presentation on it all here: http://www.slideshare.net/ravirajforyou/how-php-works. The PHP page lifecycle is on slide 3. – Sam Becker May 31 '11 at 05:55
3

The problem has nothing to do with how PHP is executed (it's bytecompiled, by the way...), but rather how the code is parsed. With that error there, the PHP parser is unable to build a working program in memory and notifies you of the syntax error.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358