Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP CompileError
In PHP 7.3 onwards, CompileError exception has been added. This class inherits the Error class. Some error conditions that previously resulted in fatal errors now throw a CompileError. This affects compilation errors that are likely to be thrown by the token_get_all() function when parsing invalid PHP syntax.
The token_get_all() function uses Zend lexical scanner to parse a given string into PHP language tokens. When used in TOKEN_PARSE mode, it can throw a CompileError for invalid PHP code.
Syntax
token_get_all ( string $source [, int $flags = 0 ] ) : array
Parameters
| Sr.No | Parameter & Description |
|---|---|
| 1 |
source PHP source code to parse |
| 2 |
flags TOKEN_PARSE − Recognizes the ability to use reserved words in specific contexts |
Example
Here's how CompileError is thrown when token_get_all() encounters invalid PHP syntax ?
<?php
try {
// Invalid PHP syntax - missing semicolon
$invalidCode = '<?php echo "Hello World"';
// This will throw CompileError in TOKEN_PARSE mode
$tokens = token_get_all($invalidCode, TOKEN_PARSE);
} catch (CompileError $e) {
echo "CompileError caught: " . $e->getMessage();
} catch (ParseError $e) {
echo "ParseError caught: " . $e->getMessage();
}
?>
CompileError caught: syntax error, unexpected end of file
Valid Code Example
For comparison, here's how valid PHP code is parsed without errors ?
<?php
try {
// Valid PHP syntax
$validCode = '<?php echo "Hello World"; ?>';
$tokens = token_get_all($validCode, TOKEN_PARSE);
echo "Parsing successful. Token count: " . count($tokens);
} catch (CompileError $e) {
echo "CompileError: " . $e->getMessage();
}
?>
Parsing successful. Token count: 7
Key Points
- CompileError was introduced in PHP 7.3
- It extends the Error class
- Mainly thrown by
token_get_all()in TOKEN_PARSE mode - Replaces fatal errors that occurred during compilation
Conclusion
CompileError provides better error handling for PHP compilation issues. Use try-catch blocks when parsing potentially invalid PHP code with token_get_all() to handle these exceptions gracefully.
