intelis
intelis

Reputation: 8068

Why do you have to include PHP file, when using namespace?

Let's say i've declared a namespace like this:

<?php
// File kitchen.php
namespace Kitchen;
?>

Why do i still have to include that file in all other files where i want to use kitchen.php
Doesn't PHP know that kitchen.php resides in Kitchen namespace?

Thanks for answers.

Upvotes: 7

Views: 10163

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46620

Namespaces make it extremely easy to create autoloaders for any class within your project as you can directly include the path to the class within the call.

An pseudo code namespace example.

<?php 
// Simple auto loader translate \rooms\classname() to ./rooms/classname.php
spl_autoload_register(function($class) {
    $class = str_replace('\\', '/', $class);
    require_once('./' . $class . '.php');
});

// An example class that will load a new room class
class rooms {
    function report()
    {
        echo '<pre>' . print_r($this, true) . '</pre>';
    }

    function add_room($type)
    {
        $class = "\\rooms\\" . $type;
        $this->{$type}  = new $class();
    }
}

$rooms = new rooms();
//Add some rooms/classes
$rooms->add_room('bedroom');
$rooms->add_room('bathroom');
$rooms->add_room('kitchen');

Then within your ./rooms/ folder you have 3 files: bedroom.php bathroom.php kitchen.php

<?php 
namespace rooms;

class kitchen {
    function __construct()
    {
        $this->type = 'Kitchen';
    }
    //Do something
}
?>

Then report classes what classes are loaded

<?php
$rooms->report();
/*
rooms Object
(
    [bedroom] => rooms\bedroom Object
        (
            [type] => Bedroom
        )

    [bathroom] => rooms\bathroom Object
        (
            [type] => Bathroom
        )

    [kitchen] => rooms\kitchen Object
        (
            [type] => Kitchen
        )

)
*/
?>

Hope it helps

Upvotes: 12

Related Questions