Using a Class in extras.php

I need to use Mobile Detect class in a project.

So I add the file to lib folder and include the path to functions.php file.

But when I try to call the class $detect = new Mobile_Detect;, this error appear:

Fatal error: Class ‘Roots\Sage\Extras\Mobile_Detect’ not found in …lib/extras.php on line 234

I try to add namespace Roots\Sage\Mobile_Detect to class file and use Roots\Sage\Mobile_Detect; to extras.php file with no success.

The use statement needs to end with the class name:

use This\Whatever\Name\Space\ClassName;

You can change the namespace declaration in the class file to:

namespace Roots\Sage;

OR, change the use statement to:

use Roots\Sage\Mobile_Detect\Mobile_Detect;


Here whats I do:

In functions.php, I call Mobile_Detect.php file before extras.php.

In Mobile_Detect.php, I add namespace Roots\Sage\Mobile_Detect;.

In extras.php, I add use Roots\Sage\Mobile_Detect\Mobile_Detect;


Totally late on the scene, just jumped back into WP dev with Sage 9.0.7. Correct me here, I aded the MobileDetect pkg via composer in the theme directory, I’m assuming the Autoloader should bring this class into the App/Controllers namespace or am I off? Can functions be extended like this or do I need to do a git clone of the repo into the app folder.

Thanks, trying to get up to speed since sage 8.5

Sorry to revive this post but wanted to show a working solution to this for others, like me, upgrading Sage v9.

The Mobile Detect library had a namespace wrapper added some time ago:

So for each file you want detection add to the head of the file:
use Detection\MobileDetect;

And then create an instance like so:
$detect = new MobileDetect;

No need to edit any source files.