PHP Accessing Global classes


When PHP parser encounters an unqulified identifier such as class or function name, it resolves to current namespace. Therefore, to access PHP's predefined classes, they must be referred to by their fully qualified name by prefixing \.

Using built-in class

In following example, a new class uses predefined stdClass as base class. We refer it by prefixing \ to specify global class


namespace testspace;
class testclass extends \stdClass{
$obj=new testclass();
echo $obj->name;

Included files will default to the global namespace. Hence, to refer to a class from included file, it must be prefixed with \


class myclass{
   function hello(){ echo "Hello World
";} } ?>

This file is included in another PHP script and its class is referred with \

when this file is included in another namespace


include 'test1.php';
class testclass extends \myclass{
function hello(){
   echo "Hello PHP
"; } } $obj1=new \myclass(); $obj1->hello(); $obj2=new testclass(); $obj2->hello(); ?>


This will print following output

Hello World
Hello PHP