全局函数什么时候不可调用?
When is a global function not a callable?
我有一个特殊的情况,我需要允许函数的外部定义,并在测试套件中使用它们。 PHP 允许您在任何地方定义全局函数 很奇怪,但它的行为似乎不一致。
如果我运行这是一个独立的脚本,$a
是true
:
function php()
{
return false;
}
$a = is_callable('php');
但是,如果我 运行 在 PHP 单元测试(测试外部定义函数的注入)中使用相同的代码,则针对同一事物的断言会失败,如下所示:
class MyTest extends TestCase
{
public function testThis()
{
function php()
{
return false;
}
self::assertTrue(is_callable('php'));
}
}
如果它明确在全局范围内,它仍然会以同样的方式失败:
class MyTest extends TestCase
{
public function testThis()
{
self::assertTrue(is_callable('php'));
}
}
function php()
{
return false;
}
根据the docs:
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
我知道嵌套函数定义必须在此之前 运行 才能访问它,但是这两个示例都这样做了。
PHPUnit 是否会阻止全局函数的定义?
最合理的解释是你的代码不在全局命名空间中。喜欢下面
<?php
namespace App;
function php() {
}
var_dump(is_callable('App\php'));
我有一个特殊的情况,我需要允许函数的外部定义,并在测试套件中使用它们。 PHP 允许您在任何地方定义全局函数 很奇怪,但它的行为似乎不一致。
如果我运行这是一个独立的脚本,$a
是true
:
function php()
{
return false;
}
$a = is_callable('php');
但是,如果我 运行 在 PHP 单元测试(测试外部定义函数的注入)中使用相同的代码,则针对同一事物的断言会失败,如下所示:
class MyTest extends TestCase
{
public function testThis()
{
function php()
{
return false;
}
self::assertTrue(is_callable('php'));
}
}
如果它明确在全局范围内,它仍然会以同样的方式失败:
class MyTest extends TestCase
{
public function testThis()
{
self::assertTrue(is_callable('php'));
}
}
function php()
{
return false;
}
根据the docs:
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
我知道嵌套函数定义必须在此之前 运行 才能访问它,但是这两个示例都这样做了。
PHPUnit 是否会阻止全局函数的定义?
最合理的解释是你的代码不在全局命名空间中。喜欢下面
<?php
namespace App;
function php() {
}
var_dump(is_callable('App\php'));