Question

Does PHP interpret code in the same way that JavaScript does? Upon some research, I've gathered that JavaScript programs are run in a so-called 'two-pass' read. The first run gets the syntax and function definitions of the program. ('Parses' the data so to speak), and the second run - well - runs the data. Does PHP work the same way? If not, how does PHP interpret code?

What are the general functions of a PHP interpreter?

Was it helpful?

Solution 2

What you've described in the question is a very tiny aspect of how the interpreter works.

PHP does indeed do this: you can tell because it is valid to have a function call higher up in the code than the actual definition of the function that is being called.

<?php
myFunction();    //this is only valid here before the function itself because of two-pass parsing.

function myFunction() {
    .....
}

myFunction();    //in a single-pass system, the function call would have to be here, after the function itself.
?>

If you only had one pass, you would only be able to call a function after the function itself had been defined. Some languages do work this way (C and Pascal are good examples). These languages require the use of header files if you want write a function call earlier in the code than the function itself is defined.

The difference is that those languages are compiled, which means that the code is only actually run once everything has been built into an executable. The single-pass approach with header files wouldn't work in an interpreted environment because while the header may allow the compiler to accept the function call as valid, an interpeter would still fail because it simply wouldn't have the function available to call.

For this reason, pretty much any interpreted language is going to use this two-pass mechanism.

However, as I said, this is just a small part of the overall design of an interpreter.

OTHER TIPS

Most programming languages work that way, maybe save for batch files. The source code is parsed into tokens and a syntax tree is created which is then evaluated. These are three separate steps and it's practically a lot simpler to keep them separated. If you'd want to mush them together so code got executed while it is being parsed, that means the parser would have to read just enough to get one full block of something which is executable, then hand that over to the runtime, which would then have to hand control back to the parser. It's a lot easier to do everything one by one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top