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

Содержание

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

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

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

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

Коментарии

for example, if you use a lot of .php files (once per class) you need to know that require() a lot of files will slow down consistently the page load

so you can use namespaces + autoload to implement package-specific initialization handlers

i used this to put an entire package (lot of classes) in one php file

!!! please note you can't use this as-is but you need to adapt it to your project

the file __init.php is placed inside every namespace/folder you want to load
there you can startup your namespace, check for environment, debugging, or as i do, you can merge all the package in one php file and require it to load other classes too.

<?php

class Loader
{
   
// here we store the already-initialized namespaces
   
private static $loadedNamespaces = array();
 
    static function 
loadClass($className)
    {
       
// we assume the class AAA\BBB\CCC is placed in /AAA/BBB/CCC.php
       
$className str_replace(array('/''\\'), DIRECTORY_SEPARATOR$className);
       
       
// we get the namespace parts
       
$namespaces explode(DIRECTORY_SEPARATOR$className);
        unset(
$namespaces[sizeof($namespaces)-1]); // the last item is the classname
       
        // now we loops over namespaces
       
$current=""; foreach($namespaces as $namepart)
        {
           
// we chain $namepart to parent namespace string
           
$current.='\\' $namepart;
           
// skip if the namespace is already initialized
           
if(in_array($currentself::$loadedNamespaces)) continue;
           
// wow, we got a namespace to load, so:
           
$fnload $current DIRECTORY_SEPARATOR "__init.php";
            if(
file_exists($fnload)) require($fnload);
           
// then we flag the namespace as already-loaded
           
self::$loadedNamespaces[] = $current;
        }

       
// we build the filename to require
       
$load $className ".php";
       
// check for file existence
       
!file_exists($load) ?: require($load);
       
// return true if class is loaded
       
return class_exists($classNamefalse);
    }
    static function 
register()
    {
       
spl_autoload_register("Loader::loadClass");
    }
    static function 
unregister()
    {
       
spl_autoload_unregister("Loader::loadClass");
    }
}

Loader::register();

?>
2011-04-22 02:09:11
http://php5.kiev.ua/manual/ru/language.namespaces.html
Автор:
The keyword 'use' has two different applications, but the reserved word table links to here.

It can apply to namespace constucts:

file1:
<?php namespace foo;
  class 
Cat 
    static function 
says() {echo 'meoow';}  } ?>

file2:
<?php namespace bar;
  class 
Dog {
    static function 
says() {echo 'ruff';}  } ?>

file3:
<?php namespace animate;
  class 
Animal {
    static function 
breathes() {echo 'air';}  } ?>

file4:
<?php namespace fub;
  include 
'file1.php';
  include 
'file2.php';
  include 
'file3.php';
  use 
foo as feline;
  use 
bar as canine;
  use 
animate;
  echo 
felineCat::says(), "<br />\n";
  echo 
canineDog::says(), "<br />\n";
  echo 
animateAnimal::breathes(), "<br />\n"?>

Note that 
felineCat::says()
should be
\feline\Cat::says()
(and similar for the others)
but this comment form deletes the backslash (why???) 

The 'use' keyword also applies to closure constructs:

<?php function getTotal($products_costs$tax)
    {
       
$total 0.00;
       
       
$callback =
            function (
$pricePerItem) use ($tax, &$total)
            {
               
               
$total += $pricePerItem * ($tax 1.0);
            };
       
       
array_walk($products_costs$callback);
        return 
round($total2);
    }
?>
2011-05-25 14:06:14
http://php5.kiev.ua/manual/ru/language.namespaces.html

    Поддержать сайт на родительском проекте КГБ