How to avoid redeclaring ticks on every file in PHP 7

自古美人都是妖i 提交于 2019-12-22 11:24:54

问题


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+?


回答1:


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



来源:https://stackoverflow.com/questions/44440613/how-to-avoid-redeclaring-ticks-on-every-file-in-php-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!