Simple Usage Example of PHP Namespace

  • 2021-11-13 06:49:50
  • OfStack

This article illustrates the simple use of the PHP namespace. Share it for your reference, as follows:

There are three files, space1. php, space2. php, use. php, in the same directory.

space1.php:


<?php
namespace MyNamespace\Factory;
class Employees{
  private $name;
  function __construct($nameStr){
    $this->name = $nameStr;
  }
  function getName(){
    return 'Factory : '.$this->name;
  }
}

space2.php:


<?php
namespace MyNamespace\Company;
class Employees{
  private $name;
  function __construct($nameStr){
    $this->name = $nameStr;
  }
  function getName(){
    return 'Company : '.$this->name;
  }
}

use. php:


<?php
// We all know that the same 1 Directory, you can't store similar files with the same name. You can store files with the same name in different directories. 
// The full name space is similar to the above meaning. 
// If there are two PHP File, it's all in the file 1 A Employees Class. In the same 1 Create two files in Employees Object, definitely not, you can use namespaces at this time. 
$DIR = dirname(__FILE__);
include($DIR.'/space1.php');
include($DIR.'/space2.php');
$obj = new MyNamespace\Factory\Employees('a');
$myName = $obj->getName();
echo "<p>$myName</p>";
$obj = new MyNamespace\Company\Employees('a');
$myName = $obj->getName();
echo "<p>$myName</p>";

Run results:

Factory : a

Company : a

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of PHP Network Programming Skills", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: