如何避免在 PHP 7 中的每个文件上重新声明刻度

How to avoid redeclaring ticks on every file in PHP 7

概览

在 PHP 5.6 中似乎添加 declare(ticks=1) 然后使用 register_tick_function() 会跟随任何包含并相应地提供分析信息。

In PHP 7+ 但是现在看来我必须在每个文件中添加 declare(ticks=1)。我用它来分析页面加载时的每个方法调用,现在不想将它添加到我系统中的每个 PHP 文件(如果它们在库中,我不能)。

我在文档中找不到关于对此所做更改的任何内容。

复制步骤

创建以下 2 个文件:

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";

结果

运行 php index.php 在终端给我:

inc.php 中取消注释 declare(ticks=1) 结果是:

问题

有什么方法可以强制它遵循 include 并在某种意义上使其在 PHP 7+ 中成为全局?

根据在 https://bugs.php.net/bug.php?id=71448

提交的 PHP 错误

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.

所以实际上这是一个错误,它曾经像在 PHP 5.6 中那样工作,并且在 PHP 7.0 中添加了正确的实现。不幸的是,这意味着它永远不会起作用,但至少有一个解释。

下面问题的答案显示了如何在 PHP 7+

中实现这一点