2012-08-21

PHP Namespaces

I've been working on a PHP project lately and when I started working on it, I remember thinking to myself that there must be the equivalent to Java packages in this language. Otherwise loading/including/referencing classes from another class can be a bit of nightmare. There is the common PHP autoload pattern, but I find this is not enough and so I kept on digging and eventually ... success! Since PHP 5.3 there is the concept of PHP Namespaces, similar to Java packages which is very helpful in creating re-usable code. Basically in your class declaration, start it off with putting your namespace definition before anything else, like so:


namespace acme\utils;

class User {
...
}
?>

And then you can re-use your class from another class or PHP file, like so:


namespace acme\business;

use acme\utils\User;

class ProcessCommand {
...
$user = new User();
...
}
?>

Hope that helps and happy PHP coding!

2 comments:

rose thomas said...

Nice,your blog is very informative.I am learn may things you mention above.
php training institute

Toddroman said...

I've been working on a PHP project and Fined out the PHP Namespaces Code Thanks For Help..

Yeah Right "Rose thomas" His Block is very informative...!!!