尝试使用我创建的名称空间时出现错误 [英] getting an error while trying to use the namespace I created
问题描述
名为tester.php的脚本
<?php
namespace my;
class Tester {
public function greet() {
echo "Hello ! <br />";
}
}
一个名为 tester1.php 的新脚本:
<?php
use my;
$obj = new Tester();
$obj->greet();
当我运行tester1.php
时,出现此错误:
When I run tester1.php
I get this error:
Warning: The use statement with non-compound name 'my' has no effect
in /opt/lampp/htdocs/tester_1.php on line 2
Fatal error: Class 'Tester' not found in /opt/lampp/htdocs/tester_1.php on line 4
为什么会出现此错误?这两个脚本都在同一目录/opt/lampp/htdocs/
中.
Why am I getting this error ? Both these scripts are in the same directory /opt/lampp/htdocs/
.
推荐答案
use
运算符用于别名化类/接口/命名空间名称,而不是导入名称空间以便使用.要使用名称空间,只需将namespace my;
放在tester1.php
文件的顶部(并且还包括原始文件,以便可以使用您的类定义).
The use
operator is meant for aliasing a class/interface/namespace name, rather than importing a namespace so it can be used. To use your namespace, you just need to put namespace my;
at the top of your tester1.php
file (and also include the original file so that your class definition is available).
<?php
namespace my;
include("tester.php");
$obj = new Tester();
$obj->greet();
如果您想为其他名称起别名,则可以使用use
,例如
If you wanted to alias to another name, then you can use use
, for example,
<?php
namespace my;
use my\Tester as Blah;
include("tester1.php");
$obj = new Blah();
$obj->greet();
这篇关于尝试使用我创建的名称空间时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!