7

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.

5
  • 10
    Namespaces != autoload. Commented Sep 27, 2012 at 22:22
  • 1
    So namespace is like virtual directory and autoload is used to actually load files from directory? Can you use autoload with namespace? Thanks!! Commented Sep 27, 2012 at 22:23
  • 1
    Read here: php.net/manual/en/language.namespaces.rationale.php and here: php.net/manual/en/language.oop5.autoload.php; reading the docs can go a long way :) Commented Sep 27, 2012 at 22:26
  • 1
    Great thanks! I am very new to all of this. Thanks for help! :) Commented Sep 27, 2012 at 22:27
  • thanks for asking @intelis, you have made all of us smarter. Commented Sep 20, 2019 at 13:31

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

1 Comment

I guess he's asking why lazy loading isn't built-in by default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.