为什么在使用命名空间时必须包含PHP文件?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了为什么在使用命名空间时必须包含PHP文件?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我已经声明了这样的命名空间:
<?PHP
// File kITchen.PHP
namespace Kitchen;
?>

为什么我仍然必须在我想使用kitchen.PHP的所有其他文件中包含该文件
PHP知道kitchen.PHP驻留在Kitchen命名空间中吗?

谢谢你的回答.

命名空间使您可以非常轻松地为项目中的任何类创建自动加载器,因为您可以直接在调用中包含类的路径.

代码名称空间示例.

<?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');

然后在你的./rooms/文件夹中你有3个文件
bedroom.PHP
bathroom.PHP
kitchen.PHP

<?PHP 
namespace rooms;

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

然后报告类加载的类

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

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

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

)
*/
?>

希望能帮助到你

脚本宝典总结

以上是脚本宝典为你收集整理的为什么在使用命名空间时必须包含PHP文件?全部内容,希望文章能够帮你解决为什么在使用命名空间时必须包含PHP文件?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。