Home  >  Article  >  Backend Development  >  PHP access global classes

PHP access global classes

王林
王林forward
2023-08-26 20:25:06747browse

PHP access global classes

Introduction

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 \.

Using built-in classes

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

Example

<?
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 \

Example

#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

Example

#test2.php
<?php
include &#39;test1.php&#39;;
class testclass extends \myclass{
function hello(){
   echo "Hello PHP"; }
}
$obj1=new \myclass();
$obj1->hello();
$obj2=new testclass();
$obj2->hello();
?>

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete