加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 18:17:10 所属栏目:PHP教程 来源:网络整理
导读:假设我已经声明了这样的命名空间: ?php// File kitchen.phpnamespace Kitchen;? 为什么我仍然必须在我想使用kitchen.php的所有其他文件中包含该文件 PHP不知道kitchen.php驻留在Kitchen命名空间中吗? 谢谢你的回答. 命名空间使您可以非常轻松地为项目中的
假设我已经声明了这样的命名空间:
<?php
// File kitchen.php
namespace Kitchen;
?>

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

谢谢你的回答.

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

伪代码名称空间示例.

<?php 
// Simple auto loader translate roomsclassname() 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] => roomsbedroom Object
        (
            [type] => Bedroom
        )

    [bathroom] => roomsbathroom Object
        (
            [type] => Bathroom
        )

    [kitchen] => roomskitchen Object
        (
            [type] => Kitchen
        )

)
*/
?>

希望能帮助到你

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读