PHP access global classes

王林
Release: 2023-08-26 20:26:02
forward
747 people have browsed it

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;
?>
Copy after login

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";}
}
?>
Copy after login

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();
?>
Copy after login

Output

This will print the following output

Hello World
Hello PHP
Copy after login

The above is the detailed content of PHP access global classes. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template