PHP Using namespaces

PHPServer Side ProgrammingProgramming

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\n";}
class myclass{
   static function hellomethod() {echo "hello in space1\n";}
}
?>

Use this file in following code

Example

 Live Demo

<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() {echo "hello in myspace\n";}
class myclass{
   static function hellomethod() {echo "hello in myspace\n";}
}
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\n";}
class myclass{
   static function hellomethod() {echo "hello in myspace\n";}
}
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\n";}
class myclass{
   static function hellomethod() {echo "hello in myspace\n";}
}
\myspace\hello();
\myspace\space1\hello();
\myspace\myclass::hellomethod();
\myspace\space1\myclass::hellomethod();
echo \myspace\MAX . "\n";
echo \myspace\space1\MAX;
?>

Output

Above code shows following output

hello in myspace
hello in space1
hello in myspace
hello in space1
200
100
raja
Published on 18-Sep-2020 09:38:03
Advertisements