在空的“ Symfony Php”上调用成员函数get()

时间:2018-11-24 07:22:10

标签: php symfony device-detection

我正在尝试获取访问我们应用程序的设备的详细信息。我已经在PHP symfony 3.4版本中集成了“ MobileDetectBundle”捆绑软件,并遵循了文档中提供的步骤。但是我在此行遇到以下错误

$mobileDetector = $this->get('mobile_detect.mobile_detector');

代码段:

$mobileDetector = $this->get('mobile_detect.mobile_detector');
$mobileDetector->isMobile();
$mobileDetector->isTablet();

错误:

"Call to a member function get() on null"

请帮助我解决此问题。

1 个答案:

答案 0 :(得分:1)

问题出在$this上,它假定是您的控制器类的实例,但为null,这意味着您正在某个尚无$this的地方(可能在控制器构造函数中)调用它。

解决方案确实是依赖注入。您最好将该服务注入到控制器中(该服务通过自动装配自动定义为服务),并在控制器内部使用它:

class MyController
{
    // ...

    protected $mobileDetector;

    public function __construct(MobileDetector $mobileDetector)
    {
        $this->mobileDetector = $mobileDetector;
        $this->mobileDetector->isMobile();
        $this->mobileDetector->isTablet();
    }

    // ...
}