Is it possible to define a global function from within a PHP namespace (within a file that has a namespace declaration)? If so, how?
<?php namespace my_module; # bunch of namespaced functions # ... # then I want to define a global function my_module() # that is an alias to my_module\mymodule()
Global space ¶Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.
By default, you can reference a globally namespaced class by adding a backslash -- eg $x = new \PDO(...); . Trying to use \ won't change that. If you want to drop the backslash from globally namespaced classes, you need to use each of them specifically.
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.
It's possible but aside from being bad design, you will have to enclose your code within brackets for each namespace and won't be able to use namespace my_module;
Instead it will have to be namespace my_module { ... }
.
Example:
namespace my_module { function module_function() { // code } } namespace { // global namespace. function my_module() { // call your namespaced code } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With