When the PHP parser encounters an unqualified identifier (such as a class or function name), it resolves to the current namespace. Therefore, to access PHP's predefined classes, you must refer to them by their fully qualified names via the prefix \.
In the following example, a new class uses the predefined stdClass as the base class. We specify the global class by adding the prefix \ to reference it
<? namespace testspace; class testclass extends \stdClass{ // } $obj=new testclass(); $obj->name="Raju"; echo $obj->name; ?>
The included files will use the global namespace by default. Therefore, to reference a class in an included file, it must be preceded by \
#test1.php <?php class myclass{ function hello(){ echo "Hello World";} } ?>
This file is included in another PHP script whose classes are referenced by \
When this file is included in another namespace
#test2.php <?php 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 the following output
Hello World Hello PHP
The above is the detailed content of PHP access global classes. For more information, please follow other related articles on the PHP Chinese website!