Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parse error in runtime-created function in PHP?

I have this simple PHP code:

<?php

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

As you see, my $code has 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 the Parse error into a variable? For example:

$error = some_func_to_get_error();
echo $error;
// Parse error: syntax error, unexpected '}' in file.php(4) : runtime-created function on line 1
like image 384
user2480690 Avatar asked Jun 25 '13 05:06

user2480690


1 Answers

I envolved with this problem about a week and at last, I found something interesting. As you know, there is a build-it function called error_get_last which return the information about 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
)

The last error occured when executing call_user_func. It needs a callback, but, the create_function didn't work correctly (as $code has parse error).

But when setting a custom error handler which return true;, so the call_user_func won't throw any error, and the last error, would be the error within the runtime-created function.

<?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 would be like this:

Array
(
    [type] => 4
    [message] => syntax error, unexpected '}'
    [file] => file.php(7) : runtime-created function
    [line] => 1
)
like image 188
user2480690 Avatar answered Oct 26 '22 21:10

user2480690