开发者

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 开发者_StackOverflow中文版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, e.g.

<?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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜