【问题标题】:"Using $this when not in object context" appears in Silex/phpunit case“不在对象上下文中使用 $this”出现在 Silex/phpunit 案例中
【发布时间】:2014-06-20 00:08:02
【问题描述】:

我有一个 Silex 应用程序,可以在本地和服务器上正常工作。只是我的 phpunit 测试在我启动它们时抛出异常(仅在服务器上,本地它们也可以工作):

“不在对象上下文中使用 $this”

我更改了代码,不再缓存防火墙,它工作正常(查看注释部分):

use Silex\Application;
use Silex\ServiceProviderInterface;

class SecurityProvider implements ServiceProviderInterface {

    //private $firewall;

    public function register(Application $app)
    {
        $app['firewall'] = $app->protect(function () use ($app) {
            // FIXME phpunit tests on server don't like the $this reference (no idea why?)
            /*if($this->firewall == null) {
                $this->firewall = new Firewall($app);
            }
            return $this->firewall;*/
            return new Firewall($app);
        });
    }

    public function boot(Application $app)
    {
    }
}

任何人知道为什么我得到了例外?

谢谢大家!

【问题讨论】:

  • 函数 () 使用 ($app, $this) { ... } ???
  • 你运行的是什么 PHP 版本?根据版本的不同,您可能需要进行不同的调整。

标签: php symfony phpunit this silex


【解决方案1】:

您在闭包内使用$this。在 5.4 之前,$this 不能在闭包内使用。从 5.4 开始,$this 指的是声明它的对象。

为了能够在 PHP 5.3 中运行你的测试,你必须使用类似的东西:

public function register(Application $app)
{
    $that = $this;

    $app['firewall'] = $app->protect(function () use ($app, $that) {
        if($that->firewall == null) {
            $that->firewall = new Firewall($app);
        }

        return $that->firewall;
    });
}

【讨论】:

  • 哇哇哇!而已!非常感谢!
猜你喜欢
  • 2014-06-11
  • 2017-09-21
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2013-12-14
  • 2015-02-12
  • 1970-01-01
相关资源
最近更新 更多