开发者

php: When to use the scope resolution symbol (::) after an include / require_once?

开发者 https://www.devze.com 2023-01-30 12:02 出处:网络
All, I\'d like to understand I\'m looking at this code sample from w3Style\'s front controller tutorial:

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 da开发者_JAVA百科y 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


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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号