171

I have a file with a class Resp. The path is:

C:\xampp\htdocs\One\Classes\Resp.php

And I have an index.php file in this directory:

C:\xampp\htdocs\Two\Http\index.php

In this index.php file I want to instantiate a class Resp.

$a = new Resp();

I know I can use require or include keywords to include the file with a class:

require("One\Classes\Resp.php");       // I've set the include_path correctly already ";C:\xampp\htdocs". It works.
$a = new Resp();

But I want to import classes without using require or include. I'm trying to understand how use keyword works. I tried theses steps but nothing works:

use One\Classes\Resp;
use xampp\htdocs\One\Classes\Resp;
use htdocs\One\Classes\Resp;
use One\Classes;
use htdocs\One\Classes;    /* nothing works */

$a = new Resp();

It says:

Fatal error: Class 'One\Classes\Resp' not found in C:\xampp\htdocs\Two\Http\index.php

How does the keyword use work? Can I use it to import classes?

2
  • 1
    You can't without importing the files. Please don't change the flow. Also namespaces really arn't used in PHP. Just like VB.NET
    – Cole Tobin
    Jun 10, 2012 at 0:00
  • 20
    @cole-johnson, not agree with you. Symfony is built around namespaces. In fact there is no any Symfony if you do not use namespaces
    – Green
    Jun 10, 2012 at 10:30

10 Answers 10

230

No, you can not import a class with the use keyword. You have to use include/require statement. Even if you use a PHP auto loader, still autoloader will have to use either include or require internally.

The Purpose of use keyword:

Consider a case where you have two classes with the same name; you'll find it strange, but when you are working with a big MVC structure, it happens. So if you have two classes with the same name, put them in different namespaces. Now consider when your auto loader is loading both classes (does by require), and you are about to use object of class. In this case, the compiler will get confused which class object to load among two. To help the compiler make a decision, you can use the use statement so that it can make a decision which one is going to be used on.

Nowadays major frameworks do use include or require via composer and psr

1) composer

2) PSR-4 autoloader

Going through them may help you further. You can also use an alias to address an exact class. Suppose you've got two classes with the same name, say Mailer with two different namespaces:

namespace SMTP;
class Mailer{}

and

namespace Mailgun;
class Mailer{}

And if you want to use both Mailer classes at the same time then you can use an alias.

use SMTP\Mailer as SMTPMailer;
use Mailgun\Mailer as MailgunMailer;

Later in your code if you want to access those class objects then you can do the following:

$smtp_mailer = new SMTPMailer;
$mailgun_mailer = new MailgunMailer;

It will reference the original class.

Some may get confused that then of there are not Similar class names then there is no use of use keyword. Well, you can use __autoload($class) function which will be called automatically when use statement gets executed with the class to be used as an argument and this can help you to load the class at run-time on the fly as and when needed.

Refer this answer to know more about class autoloader.

10
  • 1
    why not just use a different class name?
    – divine
    May 5, 2017 at 4:59
  • 23
    @divine. The classes may be from 3rd party vendors
    – Dayo
    May 10, 2017 at 17:57
  • 4
    @divine. What if both colliding classes are from 3rd parties?
    – Dayo
    May 11, 2017 at 15:01
  • 4
    @divine By convention, namespace will be <vendorName>/<packageName> so that way it's been already solved. Following convention, it is imposible for packagist to accept same vendor name from somebody else. And packagist.org is PHP repository that is used for composer installation of packages.
    – Tpojka
    Jul 28, 2017 at 14:41
  • 1
    @root does not matter, it just tells run time what is to be used. like you're driving a car and signal tell you bump ahead and you break, like way use statement will tell compiler load this for me now. Got it dear! Feb 21, 2018 at 11:35
109

use doesn't include anything. It just imports the specified namespace (or class) to the current scope

If you want the classes to be autoloaded - read about autoloading

0
39

Don’t overthink what a Namespace is.

Namespace is basically just a Class prefix (like directory in Operating System) to ensure the Class path uniqueness.

Also just to make things clear, the use statement is not doing anything only aliasing your Namespaces so you can use shortcuts or include Classes with the same name but different Namespace in the same file.

E.g:

// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;

if ($_SERVER['APP_DEBUG']) {
    // So you can utilize the Debug class it in an elegant way
    Debug::enable();
    // Instead of this ugly one
    // \Symfony\Component\Debug\Debug::enable();
}

If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html

1
  • a very usefull post my good sire
    – Desper
    Sep 5 at 7:11
9

You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the same file though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)

5

Using the keyword "use" is for shortening namespace literals. You can use both with aliasing and without it. Without aliasing you must use last part of full namespace.

<?php
    use foo\bar\lastPart;
    $obj=new lastPart\AnyClass(); //If there's not the line above, a fatal error will be encountered.
?>
1
  • I was looking for this syntax where I can import multiple classes from single file without repeating use. Useful! Oct 28, 2022 at 21:04
3

The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.

You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.

I've actually implemented one before. Here's a link.

1
  • There is a problem with it though. It needs a recursive model to allow it to build up a full path. Right now it only handles single level namespaces. Jun 10, 2012 at 0:05
3

I agree with Green, Symfony needs namespace, so why not use them ?

This is how an example controller class starts:

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class WelcomeController extends Controller { ... }

3

Can I use it to import classes?

You can't do it like that besides the examples above. You can also use the keyword use inside classes to import traits, like this:

trait Stuff {
    private $baz = 'baz';
    public function bar() {
        return $this->baz;
    }
}

class Cls {
    use Stuff;  // import traits like this
}

$foo = new Cls;
echo $foo->bar(); // spits out 'baz'
3

The use keyword is for aliasing in PHP and it does not import the classes. This really helps
1) When you have classes with same name in different namespaces
2) Avoid using really long class name over and over again.

2

Namespace is use to define the path to a specific file containing a class e.g.

namespace album/className; 

class className{
//enter class properties and methods here
}

You can then include this specific class into another php file by using the keyword "use" like this:

use album/className;

class album extends classname {
//enter class properties and methods
}

NOTE: Do not use the path to the file containing the class to be implements, extends of use to instantiate an object but only use the namespace.

1
  • Is the antislash syntax mandatory (as above answers) or can you also use slash?
    – Sandburg
    Jul 18 at 14:22

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.