关键字“使用”如何?在PHP中工作,我可以用它导入类吗? [英] How does the keyword "use" work in PHP and can I import classes with it?
问题描述
我有一个类 Resp
的文件。路径是:
I have a file with a class Resp
. The path is:
C:\xampp\htdocs\One\Classes\Resp.php
我在这个目录中有一个 index.php
文件:
And I have an index.php
file in this directory:
C:\xampp\htdocs\Two\Http\index.php
在这个 index.php
文件中,我想实例化一个类 Resp
。
In this index.php
file I want to instantiate a class Resp
.
$a = new Resp();
我知道我可以使用 require
或包含
关键字以包含具有类的文件:
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();
但我想导入类而不使用 require
或包括
。我试图了解如何使用
关键字。我尝试了这些步骤,但没有任何作用:
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();
它说:
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?
推荐答案
使用
不会包括任何东西它只是将指定的命名空间(或类)导入当前范围
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
这篇关于关键字“使用”如何?在PHP中工作,我可以用它导入类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!