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, 27 Jun 2008

view this page in

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

Съдържание

Въведение в пространствата от имена

Пространствата от имена в PHP са проектирани с цел решаване на проблеми свързани с областта на действие в големи PHP библиотеки. В PHP всички дефиниции на класове са глобални. Затова, когато авторът на библиотеката създава множество помощни класове или такива за директно използване в дадена библиотека, той трябва да е наясно, че може да съществуват и други библиотеки с подобна функционалност и по тази причина да избере уникални наименования за своите класове, за да могат тези библиотеки да се използват съвместно. Обикновено този проблем се решава с поставяне на представка - уникален низ, като например класовете, свързани с бази от данни, могат да имат представка My_Library_DB и т.н. С развитието на библиотеката се добавят още представки, което води до появата на твърде дълги имена на класове.

Пространствата от имена позволяват на разработчика да управлява именуването в съответния обхват, без да използва дълги имена всеки път, когато има обръщение към даден клас и решават проблема с поделеното глобално пространство, без кодът да става нечетим.

Пространствата от имена са достъпни от PHP 5.3.0. Този раздел е експериментален и подлежи на промени.



add a note add a note User Contributed Notes
Пространства от имена
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 | sitemap | contact | advertising | mirror sites