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

search for in the

Определение пространства имён> <Контроль типа
Last updated: Fri, 10 Oct 2008

view this page in

Пространства имён

Содержание

Обзор пространств имён

Пространства имён введены в PHP для решения проблем в больших PHP-библиотеках. В PHP все определения классов глобальны, поэтому авторы библиотек должны выбирать уникальные имена для создаваемых ими классов. Это делается для того, чтобы при использовании библиотеки совместно с другими библиотеками не возникало конфликтов имён. Обычно это достигается введением в имена классов префиксов. Например: если мы будем использовать класс dataBase - велика вероятность, что такое имя класса будет присутствовать и в других библиотеках, а при их совместном использовании возникнет ошибка. Поэтому мы вынуждены использовать для класса другое имя. Например: ourLibraryDataBase Такие действия приводят к черезмерному вырастанию длины имён классов.

Пространства имён позволяют разработчику управлять зонами видимости имён, что избавляет от необходимости использования префиксов и черезмерно длинных имён. Все это служит повышению читабельности кода.

Пространства имён доступны в PHP начиная с версии 5.3.0. Данная секция экспериментальна и возможно будет подвержена изменениям.



add a note add a note User Contributed Notes
Пространства имён
greg at chiaraquartet dot net
22-Sep-2008 06:32
the previously submitted note is incorrect.

A::foo();
is identical to
::A::foo();

in the global namespace.

The only way to successfully call the static method is to instantiate A and call it like:

<?php
$a
= new A;
$a->foo();
?>

or to use reflection.  This limitation is addressed in patches I have proposed, so the implementation may yet be usable in this regard.
nickf
01-Sep-2008 04:01
In response to Amir Abiri's comment:

In this example:
<?php
//---
// global.php
class A {
  public static function
foo() {
    echo
"static function";
  }
}

//----
// namespace.php
namespace A;
function
foo() {
  echo
"namespace function";
}
?>
The way to call each of these functions is like so:
<?php
A
::foo();  // "namespace function"
::A::foo(); // "static function"
?>
This could get pretty confusing, but at least now you know. :)
j dot s dot lubbers at gmail dot com
01-Aug-2008 01:02
This is my 'ultimate' autoload functie:
<?php
   
function __autoload($class) {
        require(
'../includes/classes/' . str_replace('::', '/', strtolower($class)) . '.php');
    }

   
//When you do:
   
$object = new PDF::Document();
?>

it will include the file:
../includes/classes/pdf/document.php

as you will notice I like to keep my includes outside the webroot.

document.php
<?php
    namespace PDF
;

    class
Document {
       
//etc...
   
}
?>
Tito
16-Jul-2008 07:31
you can use __autoload to automaticly include Classes with a "use" / "new" statement.
yarco dot w at gmail dot com
01-Jul-2008 11: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 03: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.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites