How to import and alias namespaces (Namespaces Part III)

Here you can find a short introduction to importing and aliasing namespaces in PHP >= 5.3.

First our examples from the lessons before:
test.php

<?php
namespace Test;

const TEST_IS_HERE = 1;

class Trullala {
	public function __construct() {}
	public function sayHello() {
		print „hello“;
	}
}
?>

test_me.php

<?php
namspace Test\Me;
class TestSubClass {
	public function __construct() {}
	public function sayHello() {
		print „hello from TestSubClass“;
	}
}

# Here's a function in our subnamespace.
function sayJuhu() {
	print „juhu“;
}
?>

Our main file, index.php:

<?php
require_once 'test.php';
require_once 'test_me.php';

# Import Class TestSubClass from namespace Test\Me
use Test\Me\TestSubClass;

# Use subnamespace's class TestSubClass:
$testMe = new TestSubClass();
$testMe->sayHello();

# Make an alias to the class Trullala of namespace Test
use Test\Trullala as Juhu;
$test = new Juhu();
$test->sayHello();

?>

POST A COMMENT

  • You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>