How to access a parsing error in a function created over time in PHP?

I have this simple PHP code:

<?php $code = "echo 'Hello World'; }"; call_user_func(create_function('', $code)); 

As you can see, my $code has a syntax error. When I run this, I get this result:

 Parse error: syntax error, unexpected '}' in file.php(4) : runtime-created function on line 1 Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in file.php on line 4 

How can I get an analysis error in a variable? For instance:

 $error = some_func_to_get_error(); echo $error; // Parse error: syntax error, unexpected '}' in file.php(4) : runtime-created function on line 1 
+6
source share
1 answer

I have included this issue for about a week and finally found something interesting. As you know, there is a build-it function called error_get_last which returns information about the last error. In this code:

 <?php $code = "echo 'Hello World'; }"; call_user_func(create_function('', $code)); $error = error_get_last(); 

It will return something like this:

 Array ( [type] => 2 [message] => call_user_func() expects parameter 1 to be a valid callback, no array or string given [file] => file.php [line] => 4 ) 

An error occurred while executing call_user_func last . It needs a callback, but create_function did not work correctly (since $code has a parsing error).

But when setting up a custom error handler that return true; therefore, call_user_func will not cause any errors, and the last error will be an error in the function created at runtime.

 <?php // returning true inside the callback set_error_handler(function () { return true; }); $code = "echo 'Hello World'; }"; call_user_func(create_function('', $code)); $error = error_get_last(); 

And now the error will be like this:

 Array ( [type] => 4 [message] => syntax error, unexpected '}' [file] => file.php(7) : runtime-created function [line] => 1 ) 
+3
source

Source: https://habr.com/ru/post/948034/


All Articles