12
When worked with namespaces, it is normal to see the use of use
to import classes outside the local scope:
namespace Foo;
use Bar\Classe;
use DateTime;
It is also possible to do the same with functions:
namespace Foo;
use function Bar\funcao_qualquer;
use function is_null;
Checking out the documentation about name resolution it is possible to observe that when the name to be imported refers to a function and this does not exist in the namespace current, the name will be resolved to the global scope.
For unqualified Names, if no import Rule applies and the name refers to a Function or Constant and the code is Outside the global namespace, the name is resolved at Runtime. Assuming the code is in namespace
A\B
, here is how a call to Functionfoo()
is resolved:
- It looks for a Function from the Current namespace:
A\B\foo()
.- It tries to find and call the global Function
foo()
.
Since a native function will always be solved up to the global scope naturally, there is some advantage in importing it via use
? For global constants the idea is the same?
I saw them do it in the implementation of Zend Diactoros where there is:
use function array_key_exists;
use function fclose;
use function feof;
use function fopen;
use function fread;
use function fseek;
use function fstat;
use function ftell;
use function fwrite;
use function get_resource_type;
use function is_int;
use function is_resource;
use function is_string;
use function restore_error_handler;
use function set_error_handler;
use function stream_get_contents;
use function stream_get_meta_data;
use function strstr;
use const E_WARNING;
use const SEEK_SET;
Do you know anything about this that’s not obvious or documented? It seems to me that it has no advantage because it is bringing to the current scope something that is already in the current scope. But it could be useful for some resolution mulambenta implementation problem :)
– Maniero
@Maniero The only reason I understood was to prevent these functions from being rewritten within the namespace, but I don’t know if that’s all.
– Woss