名为 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
我收到此错误: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/
.
最佳答案
use
operator用于为类/接口(interface)/命名空间名称设置别名,而不是导入命名空间以便使用。要使用你的命名空间,你只需要输入 namespace my;
在您的顶部 tester1.php
文件(并且还包括原始文件,以便您的类定义可用)。
<?php
namespace my;
include("tester.php");
$obj = new Tester();
$obj->greet();
如果你想别名到另一个名字,那么你可以使用
use
, 例如,<?php
namespace my;
use my\Tester as Blah;
include("tester1.php");
$obj = new Blah();
$obj->greet();
关于php - 尝试使用我创建的命名空间时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14930063/