Comment by blanched

1 day ago

I'm not familiar with PHP, can you elaborate on what you mean here? What is it compiling? Or are you referring to type safety?

When a php file is loaded at runtime, it runs through a very basic JIT compiler that does statically check a few things before continuing with execution. Syntax, for example, is checked for the entire file during this step.

Most type checking happens at runtime (this might not be true for interfaces at some level, but I can’t say for 100% certain - I just know I tend to see interface related errors earlier during code execution…). It’s perfectly valid syntax to declare a private method as returning an integer and then for the body of the method to return a string (explicitly cast as a string even). As long as you never call that method at runtime, no exceptions will be thrown.

With a half decent IDE or LSP, these sorts of runtime exceptions can be easily avoided but technically they still exist and if you don’t know about that, it can be argued to be confusing. PHP has made a lot of trade-offs to largely maintain backwards compatibility and many of them live in decisions that happen at runtime.

Modern PHP tooling can provide type safety in a very similar way to Typescript if you’re willing to put in the effort while also still technically offering you an escape hatch to do whatever the heck you want and duck type to your hearts content.

  • Is there a way to run type checking ahead of time similat to typescript or python's mypy or pyright?

  • One form of type checking does happen at compile time (which is really load time in PHP, but close enough), namely when a class extends another class or implements an interface: the types of every method and property are checked to ensure that they are substitutable per the standard variance rules (return types are covariant, parameters are contravariant, props are invariant). Everything else is checked at runtime though, and statically analyzing any of those is left to external tools like phpstan, psalm, or mago.

  • NIT linter warning: That’s not really a JIT compiler.

    PHP parses the whole file and compiles it to Zend opcodes before executing it, so syntax errors are caught up front. But "JIT" means compiling an intermediate representation/opcodes into native machine code at runtime, when the functions are called, not at load time when the source file is parsed. If you just load a file and never call any of its code, the JIT compiler should never compile it.

    PHP 8's OPcache JIT can do that optionally, but the normal load/parse/compile-to-opcodes step isn't JIT.