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

时间:2010-12-13 10:58:42

标签: php

所有

我想了解

我正在查看来自w3Style's front controller tutorial的代码示例:

的index.php

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

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

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

谢谢,

JDelage

4 个答案:

答案 0 :(得分:4)

FrontController似乎是Singleton class

静态调用createInstance()方法(因此::)并创建一个对象实例。然后,对结果对象执行dispatch()方法(因此->)。

答案 1 :(得分:1)

这是因为FrontController是一个带有createInstance()静态方法的类。

答案 2 :(得分:0)

当调用不需要类实例的类方法( - &gt;静态调用)时,可以通过::

调用它

答案 3 :(得分:0)

这家伙试图采用Singleton Pattern,但他的代码中存在错误:

此:

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

应该变得像:

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;
  }

这只是一种方法,但也有不同但相似的方法。这个想法是你只有这个特定类的一个实例,并且没有重复。