doufei1988
2010-12-13 10:58
浏览 41
已采纳

php:何时在include / require_once之后使用范围解析符号(::)?

All,

I'd like to understand

I'm looking at this code sample from w3Style's front controller tutorial:

index.php

<?php
define("PAGE_DIR", dirname(__FILE__) . "/pages");
require_once "FrontController.php";
FrontController::createInstance()->dispatch();

Why is the :: required in this case?

Does it have to do with the flexibility of one day creating a different class in "FrontController.php" which would also have a method of this name? Or is it to address the case when one would have several includes of different classes, all incorporating some same method name?

Thanks,

JDelage

图片转代码服务由CSDN问答提供 功能建议

全部,

我想了解 \ n

我正在查看来自 w3Style的前端控制器教程

index.php

 &lt;?php 
define(  “PAGE_DIR”,dirname(__ FILE__)。“/ pages”); 
require_once“FrontController.php”; 
FrontController :: createInstance() - &gt; dispatch(); 
   
 \  n 

为什么在这种情况下需要 ::

是否有一天在“FrontController”中创建不同类的灵活性 .php“哪个也有这个名字的方法? 或者它是为了解决这种情况,当一个人有几个包含不同的类时,都包含一些相同的方法名称?

谢谢,

JDelage < / p>

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • douquan1015 2010-12-13 11:01
    已采纳

    FrontController seems to be a Singleton class.

    The createInstance() method is called statically (hence the ::) and creates an object instance. Then, the dispatch() method is executed on the resulting object (hence the ->).

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douzhu6149 2010-12-13 11:01

    It's because FrontController is a class with a createInstance() static method.

    评论
    解决 无用
    打赏 举报
  • duanjue6575 2010-12-13 11:05

    When calling a class method which does not require a instance of the class (-> static call), you can call it by ::

    评论
    解决 无用
    打赏 举报
  • du3932066 2010-12-13 11:20

    The guy tried to adopt the Singleton Pattern but there is mistake in his code:

    This:

    class FrontController {
      public static function createInstance() {
        if (!defined("PAGE_DIR")) {
          exit("Critical error: Cannot proceed without PAGE_DIR.");
        }
        $instance = new self();
        return $instance;
      }
    

    Should become something like:

    class FrontController {
      var $instance = NULL;
      public static function createInstance() {
        if (!defined("PAGE_DIR")) {
          exit("Critical error: Cannot proceed without PAGE_DIR.");
        }
        if($this->instance == NULL) {
          $this->instance = new self();
        }
    
        return $this->instance;
      }
    

    That is just one approach but there are also different but similar. The idea is you have just one instance of this specific class and there is no duplication.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题