PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Namespace definition> <Objects and references
Last updated: Fri, 18 Jul 2008

view this page in

Namespaces

Cuprins

Namespaces overview

Namespaces in PHP are designed to solve scoping problem in large PHP libraries. In PHP, all class definitions are global. Thus, when a library author creates various utility or public API classes for the library, he must be aware of the possibility that other libraries with similar functionality would exist and thus choose unique names so that these libraries could be used together. Usually it is solved by prefixing the class names with an unique string - e.g., database classes would have prefix My_Library_DB, etc. As the library grows, prefixes add up, leading to the very long names.

The namespaces allow the developer to manage naming scopes without using the long names each time the class is referred to, and solve the problem of shared globals space without making code unreadable.

Namespaces are available in PHP as of PHP 5.3.0. This section is experimental and subject to changes.



Namespace definition> <Objects and references
Last updated: Fri, 18 Jul 2008
 
add a note add a note User Contributed Notes
Namespaces
Tito
16-Jul-2008 06:31
you can use __autoload to automaticly include Classes with a "use" / "new" statement.
yarco dot w at gmail dot com
01-Jul-2008 10:19
So do you mean if i want to use a class, i need to do extra two steps?

1) require/include that file
2) use the namespace

What about to add a trigger something like:

function __auto_namespace($names, $class)
{
  if ($class === null)
  {
    set_include_dir(implode('/', $names));
  }
  else
  {
    require_once implode('/', $names).'/'.$class.'.php';
  }
}

Then when we:
use NAMESPACE1::NAMESPACE2;
or
use NAMESPACE1::NAMESPACE2::CLASS1;

php could auto include the file we needed.
Amir Abiri
26-Dec-2007 02:31
So, if I understand correctly there is a possible ambiguity that can cause a function or method to become "masked".

If I have:

global.php:
<?php
class A
{
    static
public function foo()
    {
    }
}

A::foo(); // Will statically call method foo() of class ::A.
?>

If I now added the following to my project:

A.php:
<?php
namespace A
;

function
foo()
{
}
?>

The function call above would instead call this new function.

It shouldn't be a problem most of the time and specially if certain basic practices are followed (For example, don't name classes and namespaces the same name, and always keep different packages in their own separate namespaces), but it's something to keep in mind.

Namespace definition> <Objects and references
Last updated: Fri, 18 Jul 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites