drno94939847 2017-04-14 14:46 采纳率: 0%
浏览 154
已采纳

2具有相同类名的命名空间 - 是否需要使用“use”别名来调用第一个命名空间?

From my below code, I try to call the sayHi method, in class Cat with namespace foo; but it not work, I have to use "use" to change name to call it;

    <?php

    namespace foo;

    class Cat
    {
        public static function sayHi()
        {
            echo "Meow";
        }
    }

    namespace bar;

    class Cat
    {
        public static function sayHi()
        {
            echo "Hello";
        }
    }


    foo\Cat::sayHi();  //try to use backslash path  but Fatal error: Class 'bar\foo\Cat' not found

?>

if I use Cat::sayHi(); it always call the method from namespace bar that I don't want. so Question: Are there any method that solve this problem without use 'use' alias?

  • 写回答

1条回答 默认 最新

  • dsceme82487 2017-04-14 14:51
    关注

    When you declare a namespace, your code operates within that namespace until you declare another, or until the end of the file. You're doing this:

    namespace foo;
    class Cat {}
    namespace bar;
    class Cat {}
    // here you are in namespace bar
    foo\Cat::sayHi();
    

    Since you're already in the bar namespace, and your namespace reference doesn't anchor the root namespace, this final line is interpreted as:

    \bar\foo\Cat::sayHi();
    

    Simply anchor to the root:

    \foo\Cat::sayHi();
    

    Or put your call to foo\Cat::sayHi(); in another file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持