Cannot import/use a namespaced function in PHP
I've got a namespaced file called test.php with a function and a class:
namespace Test;
function testFunc(){}
class TestClass{}
Then if, in another file I "use" both of these namespace elements, the 开发者_运维百科class works but not the function:
use Test\testFunc,
Test\TestClass;
include "test.php";
new TestClass();
testFunc();
The TestClass object is created fine, but I get a fatal error for testFunc():
Fatal error: Call to undefined function testFunc()
I thought functions were supported with namespaces. What am I doing wrong?
EDIT: Explanation here - http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse
See http://php.net/manual/en/language.namespaces.rules.php with particular attention to:
<?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"
And
// 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"
I believe namespaced functions (port of use
keyword for function and constants) will be part of PHP 5.6
See also:
https://github.com/php/php-src/pull/526
https://wiki.php.net/rfc/use_function
From PHP 5.6 and higher you can import/use functions from other PHP files as follows:
require_once __DIR__ . "/../../path/to/your/vendor/autoload.php";
use function myprogram\src\Tools\MyFunc;
//use the imported function
MyFunc();
However, for PHP 7.0, I needed to add the function to "files" in the composer.json:
"autoload" : {
"psr-4" : {
"myprogram\\src\\" : "myprogram/src/"
},
"files" : [
"myprogram/src/Tools/ScriptWithMyFunc.php"
]
And then run composer dump-autoload
to update autoload.php.
ALTERNATIVELY:
You can also import functions from scripts directly without composer:
require_once full\path\to\ScriptWithMyFunc.php;
MyFunc();
But (at least for me) this only works when ScriptWithMyFunc.php does not have a namespace.
精彩评论