Home » Php » php – Using an external class not working as expected

php – Using an external class not working as expected

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an issue where I am trying to call a method from a class in another file. I have done: use Tests\Feature\testNameand this shows the class when I try to use it within my function and even shows the function I am trying to call within the testName file. But, when I try to run just the PHP file I get this error:

Uncaught Error: Class 'Tests\Feature\testName' not found in path\to\file

I am a little confused on why it is not working and if someone could explain why this is, I would be very grateful! 🙂

How to&Answers:

In PHP, classes are not included simply be using a use directive. You need to load them by including the file where the class is.

What is the use of use ? (haha)

use let you not using the FQDN of the class you’re using, see the piece of code below :

use \A\Long\Namespace\Foo;
$foo = new Foo();
// Without use, you would have needed : $foo = new \A\Long\Namespace\Foo();

The boring way

That’s how PHP devs used to do this many years ago, it’s just explicitly requiring the file :

// Foo.php
class Foo {}

// index.php
require_once( __DIR__ . '/Foo.php');
$foo = new Foo();

The normal way

Now, people use code that automatically load the classes with a pattern, you could use Composer (among others, won’t enter an opinion-based discussion here) or, if you project is small and you don’t want to use it because you’re not confident with it, manually load your classes. For instance, put all your classes in a class folder and name the file with the same name of the class, then you can use the following piece of code :

spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

To load all the classes you need (you probably want to put this at the beginning of your PHP code).