PHP Accessing Global classes

PHPServer Side ProgrammingProgramming


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\n";}

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\n"; }
$obj1=new \myclass();
$obj2=new testclass();


This will print following output

Hello World
Hello PHP
Updated on 18-Sep-2020 09:25:03