phpsymfonydevice-detection

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


I'am trying to get details of devices who access our application. I have integrated "MobileDetectBundle" bundle in php symfony 3.4 version and followed the steps provided in the documentation. But I am getting the following error at this line

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

Code Snippet :

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

Error :

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

Please help me to solve this issue.


Solution

  • The problem is with $this which assumed to be an instance of your controller class, but is null which means you are calling that somewhere (maybe inside controller constructor) where there is no $this yet.

    the solution indeed is Dependency Injection. you would better inject that service into your controller (which is defined as a service automatically through auto-wiring) and use it inside your controller:

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