dropbox1111 2014-12-10 18:07
浏览 114
已采纳

PHP如何实例化这个类?

I have a line of PHP that calls a new class as such:

$habits = new \Order\VO\Habits();

To me this looks like a static method call, but I can't tell what exactly is going on. I know that I have a class that follows that name space, and it is just a class that contains a bunch of variables. I can tell that this class is being instantiated, but I can't understand what the purpose for doing it in this manner is. I've never seen a class in PHP called this way, so any documentation as to what this actually is and why the class is being called in this way would be very helpful.

The project I'm in uses the Zend-Framework, so I'm not sure if this is something unique to the framework itself?

EDIT:

The way the class is being called is not a problem, I just want to understand more about what calling a class that was does, and WHY it would be better to call this specific class this way as opposed to simply using

$habits = new habits();
  • 写回答

4条回答 默认 最新

  • dongzhilian0188 2014-12-10 18:27
    关注

    A simple complete example may help. Here I'm using the braced namespace syntax to scope the code into three namespaces in the one file, \Order\VO, \Lifehacks, and the global namespace.

    <?php
    
    namespace Order\VO {
        class Habits {
            function __construct() {
                echo "New VO Habits
    ";
            }
        }
    
    }
    
    namespace Lifehacks {
        class Habits {
            function __construct() {
                echo "New Lifehack Habits
    ";
            }
        }
    }
    
    namespace {
        // PHP Fatal error:  Class 'Habits' not found
        // $foo = new Habits();
    
        // Prints "New VO Habits"
        $foo = new \Order\VO\Habits();
    
        // Prints "New Lifehack Habits"
        $bar = new \Lifehacks\Habits();
    }
    

    Note that when in the global namespace, you can't just instantiate a Habits with new Habits(), as one doesn't exist in your namespace. You have to choose one or other of the Habits classes by prefixing them with a namespace.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?