0

我试图理解 FuelPHP 是如何编写的。由于我对 OOP 了解不多,所以我对这门课感到困惑: https://github.com/fuel/core/blob/master/classes/date。 php

以下是我不明白的方法:

public static function _init()
{
    static::$server_gmt_offset  = \Config::get('server_gmt_offset', 0);

    // some code here
}

public static function factory($timestamp = null, $timezone = null)
{
    $timestamp  = is_null($timestamp) ? time() + static::$server_gmt_offset : $timestamp;
    $timezone   = is_null($timezone) ? \Fuel::$timezone : $timezone;

    return new static($timestamp, $timezone);
}

protected function __construct($timestamp, $timezone)
{
    $this->timestamp = $timestamp;
    $this->set_timezone($timezone);
}

什么叫先?__construct 做什么?什么是工厂,什么时候被使用,它返回什么——它会再次调用自己吗?初始化类后是否调用_init?我真的很困惑,有人可以帮助我理解吗?谢谢

4

2 回答 2

1

这个类看起来像是在使用工厂设计模式。在这里查找:PHP - 工厂设计模式

工厂模式允许您在运行时实例化一个类。_construct 方法在类被实例化后立即运行。

于 2011-08-12T22:40:35.590 回答
1

当一个对象被实例化时,第一个被调用的方法是 __construct() 方法。这称为构造函数,因为它有助于构造类的数据成员并执行任何其他初始化操作,然后才能调用类中的其他方法。

工厂是一种创建型设计模式,用于根据直到运行时才知道的条件创建类。- http://en.wikipedia.org/wiki/Factory_method_pattern

_init() 似乎是这个库用来设置它的类的另一种方法。

为了进一步加深您在这些领域的知识,我建议您先阅读 OOP,然后再阅读设计模式。

于 2011-08-12T22:43:41.317 回答