Namespaces in PHP

What is a Namespace?

A namespace in PHP is a way to group related classes, functions, and constants under a unique prefix. It works like a folder structure for your code and prevents class name collisions.

Example without namespaces:
If your application has a class named Controller and the Phalcon framework also has a class named Controller, PHP will not know which one you mean.

Namespaces solve this by giving each version its own “path.”

Example:

namespace MyApp\Controllers;

class Controller {
// your controller code
}

Now PHP can distinguish between:

  • MyApp\Controllers\Controller
  • Phalcon\Mvc\Controller

Why Namespaces Matter in Phalcon

Phalcon uses namespaces for all its classes. For example:

use Phalcon\Mvc\Controller;

This refers to the class whose full name is:

\Phalcon\Mvc\Controller

After importing it with use, you can simply extend it:

class IndexController extends Controller
{
public function indexAction()
{
    echo "Hello from Phalcon!";
}
}

Without the use statement, you would need the full namespace:

class IndexController extends \Phalcon\Mvc\Controller
{
}

Basic Syntax of Namespaces

Declaring a namespace in your own file

<?php

namespace MyApp\Controllers;

class ProductsController extends \Phalcon\Mvc\Controller
{
public function listAction()
{
    echo "Products list";
}
}

Importing classes with use

use Phalcon\Mvc\Controller;
use MyApp\Models\Products;

Aliasing (optional)

use Phalcon\Mvc\Controller as BaseController;

Important Rules

  • The namespace declaration must be the first PHP statement in the file.
  • A fully qualified class name (FQCN) starts with a backslash, for example:
    \Phalcon\Mvc\Controller
  • PSR-4 autoloading maps namespaces to directory structures.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *