Search code examples
phpimportinclude

How does the keyword "use" work in PHP and can I import classes with it?


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?


Solution

  • 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