Search code examples
phpinterpretervm-implementation

can we assume interpreter as a virtual machine?


I have an abstract question particularly about PHP.

Since we have we have Apache/xampp/mamp and other different packages for running PHP on different OS can we assume that PHP has sort of virtual machine? (write once and runs everywhere)


Solution

  • Ok, so even though this question is off-topic, I'll chip in:

    Is PHP a VM
    No, but PHP is a language. It started off in live as a simple toolkit, then evolved into an interpreted language, and now is a compiled language (sort of). PHP code is compiled to an intermediary language, that runs on the Zend Virtual Machine (Zend engine is the core of PHP's default runtime). So in a way, PHP is a compiled language, that runs on a VM. And yes, the point of this VM is flexibility and X-platform portability

    How does it work?
    Like any language, your source code is processed by a lexer, that translates the source into tokens
    These tokens are then parsed by the, erm, parser. The parsers job is to generate the instructions for the VM (the OP Codes, ByteCode, Intermediary language... whatever you want to call it).
    After this is done, the OP codes are executed by the Zend Virtual Machine. When the execution is over, all resources are freed, and the generated OPCodes are lost. (Of course, OP Codes are cached along the way, but that's another matter).

    This last bit is the critical difference between PHP and languages such as Java, who have a separate compiler, and offer a VM that runs ByteCode right off the bat. PHP has extensions, plugins and completely separate runtimes (like hhvm == HipHop Virtual Machine) which do offer native support for precompiled programs to be run.

    more info here

    Note
    There are people who will argue that PHP is not a compiled language, just as there are purists who will claim that it's not a programming language. But that's not the point. Besides, there is no real, clear-cut definition of either one. Some say Bash is a scripting language, others deny this. Some call Python a programming language, others don't.
    Depending on what engine you run it, JavaScript is compiled, or interpreted. Most of the engines implement a hybrid model (parts of the code are compiled, parts are interpreted). Some might even claim that, because it runs on a VM, Java isn't a real programming language. Whatever your views are on the subject, it doesn't matter.
    Debating what something is (programming language, scripting language, compiled or interpreted) is utter bull. A waste of time; time best spent writing some actual, useful code in whatever language you like.

    Even so: Like it or not, PHP runs on a Virtual Machine. End of.