Home » Php » namespaces – Use vs Include in PHP

namespaces – Use vs Include in PHP

Posted by: admin July 12, 2020 Leave a comment


I’m trying to get my head around PHP namespaces and testing with PHPUnit.

These tests from Codewars pass when I run phpunit test.php in the command line on Windows:

require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {

However, when I comment out use PHPUnit\Framework\TestCase; I get Class 'TestCase' not found which makes sense since there is no reference to the needed classes/functions.

What’s confusing me though is that lots of answers here on SO about namespacing claim that the use keyword is NOT a substitute for include/require and that the classes still need to be included/autoloaded(?).

I’m not using any autoloading here – just a solution.php file and the tests above in a test.php file.

Can someone please explain what I’m missing here? How come the tests work without any explicit including of the PHPunit functionality?

I should mention that I have PHPUnit installed globally via Composer.

How to&Answers:

To make namespaces clear (ignore load of the class file here)

So in one php-file:

namespace xyz {
  class a {}
  class b {}
namespace abc {
  use xyz\a;
  new a();
  new \xyz\b();
  class b extends a {}
namespace {
 use abc\b as aa;
 use xyz\b as bb;
 new bb;
 new aa;

Namespace are for preventing name-conflicts!


Like @deceze said, the PHPUnit did the job for you, but don’t think that use will not require the file included.

Look with atention to the structure:

PRO-TIP: Open the phpunit files that you’ll understand better.


use doesn’t include anything. It just imports the specified namespace (or class) to the current scope, you need to have an autoloader set up in order to include the file in which the namespace is defined.
Read more about autoloading here:http://php.net/manual/en/language.oop5.autoload.php

The include statement includes and evaluates the specified file.



$color = 'green';
$fruit = 'apple';



echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple



use can be usually used to shorten a Class names, when it is put at the top of class definition. But when use occurs inside a class definition, then it meant to include a Trait. https://www.w3schools.com/php/php_oop_traits.asp