2015-07-21 48 views
0

我有两个文件,第一个是test.php的,看起来像这样:PHP类,但进口

<?php 
namespace My\Namespaces\Test; 

class Test { 
    const ALERT_EMAIL = "AlertEmail"; 
    const ALERT_SMS = "AlertSms"; 
    const ALERT_NOTIFICATION = "AlertNotification"; 
} // class - EnumAlertType 
?> 

和其他文件尽量使用常量从test.php的

<?php 
use My\Namespaces\Test; 
$a = Test::ALERT_SMS; 
?> 

但我仍然得到Class 'My\Namespaces\Test' not found错误,我不确定是否正确使用名称空间。谢谢

+3

我认为这是一个打字错误,而在第二个例子中('Namespace' vs'Namespaces'),对吧?无论如何,你有没有配置自动加载(因为我没有看到你的代码中包含任何手动提及)? – Rangad

+2

也许你会'include()'这个文件,而不是'使用'这个类。 – D4V1D

+0

[Autoload classes from different folders]可能的重复(http://stackoverflow.com/questions/5280347/autoload-classes-from-different-folders) – D4V1D

回答

1

您需要在这里区分两个术语:包括导入。前者是在正在执行的当前脚本中添加代码,后者则是在代码中轻松使用它们。包括litteraly复制粘贴代码到当前脚本,以便稍后可以使用。

因此,您需要将包括require_once())类Test的代码放入将使用该代码的文件中。你确实可以在之后导入use)(特别是如果文件在分开的文件夹中)。因此,您需要:

<?php 
require_once('Test.php'); // include the code 
use My\Namespaces\Test; // import it if you want but not useful as the two file are in the same folder 
$a = Test::ALERT_SMS; // access to class constants 

您应该开始深入spl_autoloader_register()函数。

+0

嗨,我尝试使用require_once,它的工作原理,真的非常感谢你。但我仍然困惑,当我使用symfony框架,我可以直接导入其他类没有require_once(),我不知道如果symfony有什么区别.. – user2810081

+0

[当然symfony确实有所作为](http ://symfony.com/doc/current/components/class_loader/index.html)像ZF,我敢肯定,任何其他框架。 – D4V1D

+0

你是否考虑过接受这个答案,如果它解决了你的问题? – D4V1D