- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 Using namespaces
Introduction
Class, function or constant in a namespace can be used in following ways:
- Using a class in current namespace
- specifying a namespace relative to current namespace
- giving a fully qualified name of namespace
From current namespace
In this example a namespace is loaded from test1.php. Function or class name referred to without namespace accesses those in current namespace
Example
#test1.php <?php namespace myspace\space1; const MAX = 100; function hello() {echo "hello in space1
";} class myclass{ static function hellomethod() {echo "hello in space1
";} } ?>
Use this file in following code
Example
<?php namespace myspace; include 'test1.php'; const MAX = 200; function hello() {echo "hello in myspace
";} class myclass{ static function hellomethod() {echo "hello in myspace
";} } hello(); myclass::hellomethod(); echo MAX; ?>
Output
hello in myspace hello in myspace 200
Using relative namespace
In following example function and class is accesed with relative namespace
Example
<?php namespace myspace; include 'test1.php'; const MAX = 200; function hello() {echo "hello in myspace
";} class myclass{ static function hellomethod() {echo "hello in myspace
";} } space1\hello(); space1\myclass::hellomethod(); echo space1\MAX; ?>
Output
Above code shows following output
hello in space1 hello in space1 100
Fully qualified namespace
Functions and classes are given absolute namespace name
Example
<?php namespace myspace; include 'test1.php'; const MAX = 200; function hello() {echo "hello in myspace
";} class myclass{ static function hellomethod() {echo "hello in myspace
";} } \myspace\hello(); \myspace\space1\hello(); \myspace\myclass::hellomethod(); \myspace\space1\myclass::hellomethod(); echo \myspace\MAX . "
"; echo \myspace\space1\MAX; ?>
Output
Above code shows following output
hello in myspace hello in space1 hello in myspace hello in space1 200 100
- Related Articles
- PHP Namespaces Overview
- PHP Aliasing/Importing namespaces
- PHP Declaring sub-namespaces
- PHP Defining Multiple Namespaces in same file
- Is it possible to get list of defined namespaces in PHP
- What are namespaces in C#?
- Namespaces and Scoping in Python
- Namespaces and Scope in Python
- How to define namespaces in C#?
- What are nested namespaces in C#?
- Can namespaces be nested in C++?
- How to use namespaces in C++?
- What are Python namespaces all about?
- How will you explain Python namespaces in easy way?
- How will you compare namespaces in Python and C++?

Advertisements