- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP Accessing Global classes
Introduction
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
Example
<? namespace testspace; class testclass extends \stdClass{ // } $obj=new testclass(); $obj->name="Raju"; 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 \
Example
#test1.php <?php 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
Example
#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(); ?>
Output
This will print following output
Hello World Hello PHP
Advertisements