PHP致命错误:无法使用$ this作为参数
我有以下PHP方法,该方法是代码库中运行良好的一部分:
I've the following PHP method which is part of the codebase which was working fine:
<?php
class HooksTest extends DrupalTestCase {
public function testPageAlterIsLoggedIn() {
$this->drupal->shouldReceive('userIsLoggedIn')
->once()
->andReturn(TRUE);
$this->drupal->shouldReceive('drupalPageIsCacheable')
->once()
->andReturnUsing(function ($this) {
return $this;
});
$page = [];
$cacheable = $this->object->pageAlter($page);
$this->assertFalse($cacheable);
}
}
该代码之前已经通过了所有CI测试(使用phpunit
).
The code was passing all the CI tests before (using phpunit
).
但是现在当我通过php HooksTest.php
调用文件时,出现以下错误:
However now when I'm invoking the file via php HooksTest.php
, I've got the following error:
PHP致命错误:无法在第11行的
HooksTest.php
中使用$this
作为参数
PHP Fatal error: Cannot use
$this
as parameter inHooksTest.php
on line 11
致命错误:无法在第11行的HooksTest.php
中使用 $this
作为参数
Fatal error: Cannot use $this
as parameter in HooksTest.php
on line 11
我已经用PHP 7.1、7.2和相同的问题进行了测试.我相信它可以在PHP 5.6中使用.
I've tested with PHP 7.1, 7.2 and same issue. I believe it was working in PHP 5.6.
如何将上述代码转换为具有相同含义?
How can I convert above code to have the same meaning?
从功能参数中删除$this
是否足够?
Does removing $this
from the function parameter should be enough?
只需跳过$this
参数,即可更改
Just skip $this
argument, change
function ($this) {
return $this;
}
到
function () {
return $this;
}
查看示例#5在
Look at Example #5 Automatic binding of $this
on Anonymous functions page:
<?php
class Test
{
public function testing()
{
return function() {
var_dump($this);
};
}
}
$object = new Test;
$function = $object->testing();
$function();
?>