zoukankan      html  css  js  c++  java
  • PHP命名空间(Namespace)的使用简介

    原文链接:https://www.cnblogs.com/zhouguowei/p/5200878.html

     可以导入命名空间也可以导入命名空间的类

    <?php 
    namespace BlogArticle;
    class Comment{}
     
    //创建一个BBS空间
    namespace BBS;
     
    //导入一个命名空间
    use BlogArticle;
    //导入命名空间后可使用限定名称调用元素
    $article_comment = new ArticleComment();
     
    //为命名空间使用别名
    use BlogArticle as Arte;
    //使用别名代替空间名
    $article_comment = new ArteComment();
     
    //导入一个类
    use BlogArticleComment;
    //导入类后可使用非限定名称调用元素
    $article_comment = new Comment();
     
    //为类使用别名
    use BlogArticleComment as Comt;
    //使用别名代替空间名
    $article_comment = new Comt();
    ?>

    注意:use不等于require_once或者include,use的前提是已经把文件包含进当前文件。https://www.cnblogs.com/jiqing9006/p/5406994.html

    如果使用了use,下面再new的时候就可以用别名,不然就要new一个完整路径的类,就像tp5快速入门->基础->视图:

    [ 新手须知 ]
    这里使用了use来导入一个命名空间的类库,然后可以在当前文件中直接使用该别名而不需要使用完整的命名空间路径访问类库。也就说,如果没有使用
    
    use thinkController;
    就必须使用
    
    class Index extends 	hinkController
    这种完整命名空间方式。

    如果导入元素的时候,当前空间有相同的名字元素将会怎样?显然结果会发生致命错误。

    <?php 
    namespace BlogArticle;
    class Comment{}
     
    //创建一个BBS空间
    namespace BBS;
    class Comment{}
    class Comt{}
     
    //导入一个类
    use BlogArticleComment;
    $article_comment = new Comment();//与当前空间的Comment发生冲突,程序产生致命错误
     
    //为类使用别名
    use BlogArticleComment as Comt;
    $article_comment = new Comt();//与当前空间的Comt发生冲突,程序产生致命错误
    ?>

    但是可以这样用就不会报错

    <?php
    namespace BlogArticle;
    class Comment{
        function aa(){
            echo 33;
        }
    }
    
    //创建一个BBS空间
    namespace BBS;
    class Comment{}
    class Comt{}
    
    //导入一个类
    //use BlogArticleComment;
    $article_comment = new BlogArticleComment();//正确//为类使用别名
    //use BlogArticleComment as Comt;
    $article_comment = new BlogArticleComment();//正确
    $article_comment->aa();//输出33
    ?>
  • 相关阅读:
    C++ 面向对象高级开发 -- static
    C++ 面向对象高级开发 -- complex 类的实现
    单独编译PCL的kdtree模块报错“undefined reference to”
    【C++】预处理指令#define,#ifdef,#ifndef,#endif ...
    点云配准(Registration)算法——以PCL为例
    算法岗求职资料汇总
    C++面向对象高级开发
    opencv的常用头文件
    ubuntu下,VSCode采用cmake编译C++工程
    "error while loading shared libraries: xxx.so.x" 错误的原因和解决办法
  • 原文地址:https://www.cnblogs.com/gavinyyb/p/9235287.html
Copyright © 2011-2022 走看看