Using namespaces: fallback to global function/constant

(PHP 5 >= 5.3.0)

Inside a namespace, when PHP encounters a unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, One must refer to them with their fully qualified Name as in:

Przykład #1 Accessing global classes inside a namespace

namespace A\B\C;
Exception extends \Exception {}

$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception

$c = new ArrayObject// fatal error, class A\B\C\ArrayObject not found

For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

Przykład #2 global functions/constants fallback inside a namespace

namespace A\B\C;

    return \
strlen($str) - 1;

E_ERROR"\n"// prints "45"
echo INI_ALL"\n"// prints "7" - falls back to global INI_ALL

echo strlen('hi'), "\n"// prints "1"
if (is_array('hi')) { // prints "is not array"
echo "is array\n";
} else {
"is not array\n";

add a note add a note

User Contributed Notes 2 notes

markus at malkusch dot de
3 months ago
You can use the fallback policy to provide mocks for built-in functions like time(). You therefore have to call those functions unqualified:

namespace foo;

time() {

assert (1234 == time());

However there's a restriction that you have to define the mock function before the first usage in the tested class method. This is documented in Bug #68541.

You can find the mock library php-mock at GitHub.
cory at xison dot ca
10 months ago
I want to throw it out there, I found the following easier to deal with when porting parts of some older code into a new project in regards to accessing global classes.

namespace app\somethingorother;
use \
core as core;



I know it's not exactly the same as the solutions mentioned above, but it works for what I'm trying to accomplish.
To Top