Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 967
intelis Avatar asked Sep 27 '12 22:09

intelis


1 Answers

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

like image 111
Lawrence Cherone Avatar answered Oct 21 '22 04:10

Lawrence Cherone