Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP Namespaces

Tags:

namespaces

php

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?

like image 724
John Avatar asked Nov 11 '10 09:11

John


2 Answers

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.

like image 91
Gordon Avatar answered Nov 13 '22 07:11

Gordon


// people.php
<?php
namespace People;

class People {}


// managers.php
<?php
namespace Managers;

require_once __DIR__.'/people.php';

class People extends \People\People {}
like image 28
Stefan Gehrig Avatar answered Nov 13 '22 08:11

Stefan Gehrig