【问题标题】:Is the function in namespace code running into infinite loop or what?命名空间代码中的函数是运行到无限循环还是什么?
【发布时间】:2018-06-15 15:38:52
【问题描述】:

我正在使用 PHP 7.2.1

考虑下面的代码:

<?php
namespace A\B\C;

const E_ERROR = 45;
function strlen($str)
{
    return strlen($str) - 1;
}

echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL

echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
    echo "is array\n";
} else {
    echo "is not array\n";
}
?>

输出:

45 
7 

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 262144 bytes) in ... on line 7

据我所知,如果命名空间函数不存在,PHP 将回退到全局函数。

那为什么我在这里收到致命错误

另外,我收到的致命错误是否意味着程序正在运行无限循环?如果是,如何?如果不是,这个致命错误的确切含义是什么?

【问题讨论】:

  • 我所看到的只是“命名空间”函数存在......
  • "如果命名空间函数不存在则回退到全局函数" – 好吧,但是 strlen 确实 存在于你的命名空间中,并且这是一个无限递归函数。当然,它唯一能做的就是内存不足。
  • 同:function myfunc($num) { return myfunc($num) - 1; } 使用return \strlen($str) - 1; 让它调用内置的PHP。
  • @deceze 我的意思是,老实说,我本以为它会超出某种垂直方向的内存结构...:3c
  • @Sammitch 啊,像筒仓排气?是的,同样的区别。

标签: php function namespaces global built-in


【解决方案1】:

是的,您使用的代码确实在无限循环中运行。这是我的测试结果的样子(信息量更大):

~ » php test.php
45
7
PHP Fatal error:  Maximum function nesting level of '256' reached, 
aborting! in /Users/xxx/test.php on line 5

如果您已经覆盖了 std php 函数(我不建议这样做),那么您必须通过在 std 函数前面加上反斜杠来显式运行它(使用全局命名空间)。

<?php
namespace A\B\C;

const E_ERROR = 45;
function strlen($str)
{
    return \strlen($str) - 1;
}

echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL

echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
    echo "is array\n";
} else {
    echo "is not array\n";
}

结果:

~ » php test.php
45
7
1
is not array

编辑:直到现在我才发现这本手册有一个非常相似的例子:http://php.net/manual/en/language.namespaces.global.php

【讨论】:

    猜你喜欢
    • 2013-07-25
    • 2014-01-05
    • 2011-03-23
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    相关资源
    最近更新 更多