Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Accessing Global classes
When PHP parser encounters an unqualified 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 Classes
In following example, a new class uses predefined stdClass as base class. We refer it by prefixing \ to specify global class ?
<?php
namespace testspace;
class testclass extends \stdClass{
//
}
$obj = new testclass();
$obj->name = "Raju";
echo $obj->name;
?>
Raju
Accessing Classes from Included Files
Included files will default to the global namespace. Hence, to refer to a class from included file, it must be prefixed with \.
Creating a Global Class
First, let's create a file with a class in global namespace ?
// test1.php
<?php
class myclass{
function hello(){
echo "Hello World<br>";
}
}
?>
Including and Extending Global Class
When this file is included in another namespace, we must use \ to access the global class ?
<?php
// Simulating included content
class myclass{
function hello(){
echo "Hello World<br>";
}
}
namespace testspace;
class testclass extends \myclass{
function hello(){
echo "Hello PHP<br>";
}
}
$obj1 = new \myclass();
$obj1->hello();
$obj2 = new testclass();
$obj2->hello();
?>
Hello World Hello PHP
Conclusion
Always prefix global classes and functions with \ when working within namespaces to ensure proper resolution. This applies to both PHP's built-in classes and user-defined classes from included files.
