Search code examples
php-5.3

namespace in php


<?php
namespace foo;
use My\Full\Classname as Another;

// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;

// importing a global class
use ArrayObject;

$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
?> 

Please help me with this.

What is the meaning of use My\Full\Classname as Another;


Solution

  • Thats an alias. Every time you refer Another as a (relative) namespace, or classname, it gets resolved to \My\Full\Classname

    $x = new Another;
    echo get_class($x); // "\My\Full\Classname"
    $y = new Another\Something;
    echo get_class($y); // "\My\Full\Classname\Something"
    

    Identifiers starting with a namespace separator \ are full-qualified names. If it's missing, the identifiers are resolved against the current namespace and against the alias definitions defined by use (in this order) (except for identifiers in use and namespace: They are always full-qualified).

    PHP-Manual: Namespaces