Chapter 1: How PHP Executes—from Source Code to Render

by Thomas Punt

Introduction

  1. Lexing
  2. Parsing
  3. Compilation
  4. Interpretation

Stage 1 - Lexing

$code = <<<'code'
<?php
$a = 1;
code;

$tokens = token_get_all($code);

foreach ($tokens as $token) {
    if (is_array($token)) {
        echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
    } else {
        var_dump($token);
    }
}
Line 1: T_OPEN_TAG ('<?php
')
Line 2: T_VARIABLE ('$a')
Line 2: T_WHITESPACE (' ')
string(1) "="
Line 2: T_WHITESPACE (' ')
Line 2: T_LNUMBER ('1')
string(1) ";"

Stage 2 - Parsing

$code = <<<'code'
<?php
$a = 1;
code;

print_r(astparse_code($code, 30));
astNode Object (
    [kind] => 132
    [flags] => 0
    [lineno] => 1
    [children] => Array (
        [0] => astNode Object (
            [kind] => 517
            [flags] => 0
            [lineno] => 2
            [children] => Array (
                [var] => astNode Object (
                    [kind] => 256
                    [flags] => 0
                    [lineno] => 2
                    [children] => Array (
                        [name] => a
                    )
                )
                [expr] => 1
            )
        )
    )
)
  • kind - An integer value to depict the node type; each has a corresponding constant (e.g. AST_STMT_LIST => 132, AST_ASSIGN => 517, AST_VAR => 256)
  • flags - An integer that specifies overloaded behaviour (e.g. an astAST_BINARY_OP node will have flags to differentiate which binary operation is occurring)
  • lineno - The line number, as seen from the token information earlier
  • children - sub nodes, typically parts of the node broken down further (e.g. a function node will have the children: parameters, return type, body, etc)

Stage 3 - Compilation

if (PHP_VERSION === '7.1.0-dev') {
    echo 'Yay', PHP_EOL;
}
php -dopcache.enable_cli=1 -dopcache.optimization_level=0 -dvld.active=1 -dvld.execute=0 file.php
Output
php -dopcache.enable_cli=1 -dopcache.optimization_level=1111 -dvld.active=-1 -dvld.execute=0 file.php
Output

Stage 4 - Interpretation

Conclusion

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset