Domanda

In php.net there is an example that I didn't understand:

<?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
?>

From here: http://www.php.net/manual/en/language.namespaces.importing.php

How can they say in this statement $obj = new namespace\Another; that it instantiate an object from the class foo\another? When I tried to add a definition to the class Another I got an error that says that the Another name is already in use (because it is an alias).

È stato utile?

Soluzione

This works if the foo\Another class is defined in another file without such alias.

another.php

<?php

namespace foo;

class Another { }

test.php

<?php

namespace foo;
use My\Full\Classname as Another;

require_once 'another.php';

new namespace\Another;

The example given is to illustrate namespace resolution and conveniently ignores other details and conflicts which may arise.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top