Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define global function from within PHP namespace

Tags:

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() 
like image 492
ryanve Avatar asked Dec 03 '12 23:12

ryanve


People also ask

What is global namespace in PHP?

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.

How do I use global 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.

Are functions global in PHP?

$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.

Does PHP have namespace?

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.


1 Answers

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     } } 
like image 159
drew010 Avatar answered Sep 22 '22 01:09

drew010