Home » Php » class – Why do you have to include PHP file, when using namespace?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&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