Alex Rivera | Logout

Using PHP Namespaces

Asked 2010-11-11T09:04:56.443
22

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?

Edit
Report

1 Answer

32

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.

answered 2010-11-11T09:20:48.083

Your Answer