๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Namespaces

A namespace is a named space that groups classes under one prefix. The prefix keeps two classes with the same short name apart.

Use imports the shop cart

The cart file sets the Shop prefix on its Cart class. The use line imports that class, so the short name Cart builds it.

<?php
require "cart.php";
use Shop\Cart;
$cart = new Cart();
$cart->add();
$cart->add();
echo $cart->items . "\n";

Two classes share one short name

The main file declares its own Cart class in the global space. A plain new Cart builds the global class, and the full name with a leading backslash builds the shop class.

<?php
require "cart.php";
class Cart {
  public $label = "Global cart";
}
$own = new Cart();
echo $own->label . "\n";
$shop = new \Shop\Cart();
$shop->add();
echo $shop->items . "\n";

An alias shortens an imported name

The as word gives the imported class the alias ShopCart. The alias builds the same shop class under a shorter name.

<?php
require "cart.php";
use Shop\Cart as ShopCart;
$cart = new ShopCart();
$cart->add();
$cart->add();
$cart->add();
echo $cart->items . "\n";

Example

<?php
require "cart.php";
use Shop\Cart as ShopCart;
class Cart {
  public $label = "Gift cart";
}
$own = new Cart();
$shop = new ShopCart();
$shop->add();
$shop->add();
echo "Checkout: " . $own->label . " plus " . $shop->items . " shop items\n";

Key points

  • The namespace line at the top of a file sets the prefix for the classes in that file.
  • A class in a namespace has a full name built from the prefix and the short name.
  • The use statement imports a class so the short name works on its own.
  • A name that starts with a backslash is read from the global space.
  • The as word in a use statement gives the class an alias.

In this example, require loads the cart file. The alias ShopCart names the shop class, and the main file declares its own Cart class with a label. The checkout line joins the label from one class with the item count from the other.

Note

A namespace groups names only and loads no files, so a require line is still needed.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the as word do in a use statement?