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 ParseError
ParseError class extends CompileError class and is thrown when PHP code inside a string passed to the eval() function contains syntax errors.
The eval() function evaluates a given string as PHP code. If the code contains syntax errors, it throws a ParseError instead of causing a fatal error.
Syntax
eval ( string $code ) : mixed
Parameters
| Parameter | Description |
|---|---|
| code | Valid PHP code to be evaluated. Must not include opening/closing PHP tags and must end with semicolon. |
Valid code returns NULL, while syntax errors in the code throw a ParseError exception.
Example
The following example demonstrates how ParseError is thrown when invalid syntax is passed to eval() −
<?php
$a = 10;
try {
eval('$a = $a + ;'); // Missing operand after +
} catch (ParseError $e) {
echo "Parse Error: " . $e->getMessage();
}
?>
Parse Error: syntax error, unexpected ';'
Complete Example with Multiple Scenarios
Here's a more comprehensive example showing different ParseError scenarios −
<?php
function testParseError($code, $description) {
echo "Testing: $description<br>";
try {
eval($code);
echo "Success<br>";
} catch (ParseError $e) {
echo "ParseError: " . $e->getMessage() . "<br>";
}
echo "---<br>";
}
// Test cases
testParseError('$x = 5;', 'Valid syntax');
testParseError('$x = ;', 'Missing value');
testParseError('echo "Hello"', 'Missing semicolon');
testParseError('$x = 5 + ;', 'Incomplete expression');
?>
Testing: Valid syntax Success --- Testing: Missing value ParseError: syntax error, unexpected ';' --- Testing: Missing semicolon ParseError: syntax error, unexpected end of file --- Testing: Incomplete expression ParseError: syntax error, unexpected ';' ---
Conclusion
ParseError provides a way to handle syntax errors in dynamically evaluated PHP code gracefully. Always use try-catch blocks when using eval() to prevent fatal errors and handle syntax issues properly.
