> const DEBUG_MODE = false;
> 
> function foo() {
>  if (DEBUG_MODE) {
>    // Do stuff.
>  }
> }
> 
> PHP will currently (AIUI) inline the DEBUG_MODE value at compile time,
> notice that the code path is unreachable, and omit it from the compiled 
> opcodes entirely.
> (I'm pretty sure it does that now, at least; if not, it certainly can be.)

It actually can't do that safely for global constants.
(But it can and does do that for class constants, *within the class*)
For example, if you declare a constant twice (declare() or const DEBUG_MODE =), 
then php emits a notice, but continues executing keeping the value the constant 
previously had.
You can use opcache's debug output to confirm that.

php -d zend_extension=opcache.so -d opcache.enable_cli=1  \
   -d opcache.file_cache= -d opcache.opt_debug_level=0x20000 example.php

```
<?php

const DEBUG = false;
class TempClass {
    const DEBUG = false;
    public function main() {
        if (DEBUG) { echo "In debug for global\n"; }
        if (TempClass::DEBUG) { echo "In debug for class const\n"; }  // 
optimized out
    }
}
/*
L0 (7):     T0 = FETCH_CONSTANT string("DEBUG")
L1 (7):     JMPZ T0 L4
L2 (7):     ECHO string("In debug for global
")
L3 (9):     RETURN null
L4 (9):     RETURN null
 */
```

A 'static const' syntax enforcing that constants can only be declared in one 
place would help in making these sorts of optimizations easier
(with changes to opcache, for expressions that can be evaluated at compile time)
But so would preloading in the future, since php could likely recompile 
functions with the constants known from the preload script
(maybe it does this already).
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to