简体   繁体   中英

Using PHP Namespaces

I have been searching websites to try and get a handle on using PHP namespaces, but they all seem quite vague but what they're trying to do is easy to understand!

My question is: I have a file called people.php and in it is defined class called people . If I create another file called managers.php in the same folder can I define a class again called people which extends the original people class but in the namespace of managers , if so do I have to 'include' the original people.php and if so do I put the include after the writing: namespace managers ?

Namespaces are a way to group your related classes in packages. What you describe could best be put under a single namespace like

<?php // people.php
namespace com\example\johnslibrary\people;
abstract class People {

}

and then

<?php // manager.php
namespace com\example\johnslibrary\people;
require_once 'path/to/People.php'; // can better use autoloading though
class Manager extends People {

}

because a Manager is a subclass of People, so there is not much of a reason to put them into their own namespace. They are specialized People.

If you want to Managers to be in their own namespace, you can do so, but have to use the fully qualified name when using the extends keyword, eg

<?php // manager.php
namespace com\example\johnslibrary\managers;
require_once 'path/to/People.php';
class Manager extends \com\example\johnslibrary\people\People {

}

or import the People class first

<?php // manager.php
namespace com\example\johnslibrary\managers;
use com\example\johnslibrary\People as People;
require_once 'path/to/People.php';
class Manager extends People {

}

See the PHP Manual on Namespaces for extensive documentation.

// people.php
<?php
namespace People;

class People {}


// managers.php
<?php
namespace Managers;

require_once __DIR__.'/people.php';

class People extends \People\People {}

I have old PHP Class and i need to use it in new PHP file as for example: index.php has to use iClass.php . But before using the OLD iClass.php i have to modify it as below, so that i can use it in index.php.

iClass.php:

namespace ic;
class iClass {
  public static function callMeFromClass() {
    echo 'OK - you have called me!';
    exit;
  }
}

index.php

namespace inex;
require_once 'iClass.php';
use ic\iClass;
iClass::callMeFromClass();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM