Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid redeclaring ticks on every file in PHP 7

Tags:

php

profiling

Overview

In PHP 5.6 it seems that adding declare(ticks=1) and then using register_tick_function() would follow any includes and provide profiling information accordingly.

In PHP 7+ however it now seems I have to add declare(ticks=1) in every file. I use this for profiling every method call on a page load and don't now want to add this to each PHP file in my system (some I can't if they are in libraries).

I can't find anything in the docs about changes that were made to this.

Replication Steps

Create the below 2 files:

index.php

<?php

declare(ticks=1);
$count = 0;

register_tick_function('ticker');
function ticker() {
  global $count;
  $count++;
}

$foo = 'foo';
$bar = 'bar';

include dirname(__FILE__) . '/inc.php';

echo $count;

inc.php

<?php

#declare(ticks=1);

$baz = "baz";
$qux = "qux";

Results

Running php index.php in the terminal gives me:

  • PHP 5.6 - 7
  • PHP 7.0 - 5

With declare(ticks=1) uncommented in inc.php the results are:

  • PHP 5.6 - 8
  • PHP 7.0 - 8

Question

Is there any way to way to force it to follow includes and in a sense make it global in PHP 7+?

like image 574
Peter Featherstone Avatar asked Dec 12 '25 04:12

Peter Featherstone


1 Answers

According to the PHP bug filed at https://bugs.php.net/bug.php?id=71448

Due to an implementation bug, the declare(ticks=1) directive leaked into different compilation units prior to PHP 7.0. This is not how declare() directives, which are per-file or per-scope, are supposed to work.

So in fact it was a bug that it ever did work as it did in PHP 5.6 and the correct implementation has been added in PHP 7.0. Unfortunately this means it will never work but at least there is an explanation.

There is an answer on the below question that shows how to achieve this in PHP 7+

Natively profile multiple scripts in PHP7

like image 54
Peter Featherstone Avatar answered Dec 13 '25 19:12

Peter Featherstone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!