Roots Discourse

Using a Class in extras.php


#1

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.


#2

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;

#3

Nice.

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;

Thanks!


#4

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