In PHP, when the parser encounters an unqualified identifier (such as a class or function name), it defaults to parsing it as the current namespace. Therefore, to access PHP's predefined classes, you must reference them by their fully qualified name using the \
Included files will default to the global namespace. Therefore, to reference a class from an included file, you must add the \ prefix to the class name.
# test1.php <?php class myclass { function hello() { echo "Hello World"; } } ?>
When this file is included in another PHP script, the class must be referenced with the \ prefix.
# 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(); ?>
When running the above code, you will see the following output:
Hello World Hello PHP
Through the above examples, you can clearly understand how to access global classes in PHP and how to reference them across different namespaces.