【问题标题】:Call to a member function get() on null "Symfony Php"在 null "Symfony Php" 上调用成员函数 get()
【发布时间】:2018-11-24 07:22:10
【问题描述】:

我正在尝试获取访问我们应用程序的设备的详细信息。我已经在 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"

请帮我解决这个问题。

【问题讨论】:

    标签: php symfony device-detection


    【解决方案1】:

    问题在于$this,它假定是您的控制器类的一个实例,但它为 null,这意味着您正在调用它的某个地方(可能在控制器构造函数中),而那里还没有 $this

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

    class MyController
    {
        // ...
    
        protected $mobileDetector;
    
        public function __construct(MobileDetector $mobileDetector)
        {
            $this->mobileDetector = $mobileDetector;
            $this->mobileDetector->isMobile();
            $this->mobileDetector->isTablet();
        }
    
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2021-01-23
      • 2017-09-14
      • 2017-12-06
      相关资源
      最近更新 更多