如何解决无法导入/使用PHP中的命名空间函数
| 我有一个名为test.php的命名空间文件,其中包含一个函数和一个类:namespace Test;
function testFunc(){}
class TestClass{}
然后,如果我在另一个文件中“使用”这两个名称空间元素,则该类起作用但该函数无效:
use Test\\testFunc,Test\\TestClass;
include \"test.php\";
new TestClass();
testFunc();
TestClass对象创建得很好,但是我遇到了致命的testFunc()错误:
Fatal error: Call to undefined function testFunc()
我认为名称空间支持功能。我究竟做错了什么?
编辑:此处的解释-http://www.php.net/manual/zh-CN/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse
解决方法
请参阅http://php.net/manual/en/language.namespaces.rules.php,并特别注意:
<?php
namespace A;
use B\\D,C\\E as F;
// function calls
foo(); // first tries to call \"foo\" defined in namespace \"A\"
// then calls global function \"foo\"
\\foo(); // calls function \"foo\" defined in global scope
my\\foo(); // calls function \"foo\" defined in namespace \"A\\my\"
F(); // first tries to call \"F\" defined in namespace \"A\"
// then calls global function \"F\"
和
// static methods/namespace functions from another namespace
B\\foo(); // calls function \"foo\" from namespace \"A\\B\"
B::foo(); // calls method \"foo\" of class \"B\" defined in namespace \"A\"
// if class \"A\\B\" not found,it tries to autoload class \"A\\B\"
D::foo(); // using import rules,calls method \"foo\" of class \"D\" defined in namespace \"B\"
// if class \"B\\D\" not found,it tries to autoload class \"B\\D\"
\\B\\foo(); // calls function \"foo\" from namespace \"B\"
\\B::foo(); // calls method \"foo\" of class \"B\" from global scope
// if class \"B\" not found,it tries to autoload class \"B\"
,我相信命名空间函数(用于函数和常量的use
关键字端口)将成为PHP 5.6的一部分
也可以看看:
https://github.com/php/php-src/pull/526
https://wiki.php.net/rfc/use_function
,在PHP 5.6和更高版本中,您可以按如下方式从其他PHP文件导入/使用函数:
require_once __DIR__ . \"/../../path/to/your/vendor/autoload.php\";
use function myprogram\\src\\Tools\\MyFunc;
//use the imported function
MyFunc();
但是,对于PHP 7.0,我需要将该函数添加到composer.json中的\“ files \”中:
\"autoload\" : {
\"psr-4\" : {
\"myprogram\\\\src\\\\\" : \"myprogram/src/\"
},\"files\" : [
\"myprogram/src/Tools/ScriptWithMyFunc.php\"
]
然后运行composer dump-autoload
更新autoload.php。
替代地:
您也可以直接从脚本中导入函数,而无需composer:
require_once full\\path\\to\\ScriptWithMyFunc.php;
MyFunc();
但是(至少对我来说),这仅在ScriptWithMyFunc.php没有名称空间时才有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。