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条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真