Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run a PHP function after each line of a PHP script is executed?

Tags:

php

apache

My question is similar to this: Is it possible to run code after each line in Ruby? However I want to do it in PHP.

Is it possible and if so, how?

like image 502
Tim Avatar asked Jun 02 '11 13:06

Tim


3 Answers

You can register a tick handler:

Ticks

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.

As you can see, it's not exactly as "each line of code" unless you only write one tickable statement each line. But it's the closest you can get.

Example:

declare(ticks=1);
register_tick_function(function() {
    echo "tick_handler() called\n";
});

echo 'Line 1', PHP_EOL;
echo 'Line 2', PHP_EOL;
echo strtoupper('Line 3'), PHP_EOL;

will output (demo):

tick_handler() called
Line 1
tick_handler() called
Line 2
tick_handler() called
LINE 3
tick_handler() called
like image 165
Gordon Avatar answered Nov 02 '22 01:11

Gordon


I don't think it is within PHP. You could, however, write a PHP script that took your original script and inserted an extra line after each line of the original.

like image 42
Skilldrick Avatar answered Nov 02 '22 02:11

Skilldrick


You could try putting a wrapper around your original PHP, like so:

<?PHP
$lines = file('original.php');

foreach ($lines as $line) {
    eval($line);
    your_function();
}
?>
like image 1
Dan Avatar answered Nov 02 '22 02:11

Dan