kphp icon indicating copy to clipboard operation
kphp copied to clipboard

Add a predefined const to make it possible to check whether the code runs in PHP or KPHP

Open quasilyte opened this issue 3 years ago • 0 comments

Adding this snippet to every real-world library is tiresome:

#ifndef KPHP
define('kphp', 0);
if (false)
#endif
  define('kphp', 1);

Perhaps we can do better?

What about this pattern?

if (defined('KPHP')) {
  // KPHP code.
} else {
  // PHP code.
}

Even if we don't use kphp-polyfills, normal PHP would evaluate defined("KPHP") to false and execute the correct branch. For KPHP, using defined("KPHP") should always evaluate to true.

We need to:

  • Make sure this pattern works as expected.
  • Add tests so this pattern remain correct in the future.
  • Update docs and kphp snippets to use this new pattern.

I think it's superior to the approach we're currently suggesting. People really do insert that define for the constant everywhere. It could be worse if several unrelated projects try to define that constant (which can be real if people develop independent composer packages that need to do a KPHP/PHP branching).

quasilyte avatar Nov 02 '21 23:11 quasilyte