Question

I'm trying to undestand how FuelPHP was written.. And since I don't know OOP much, I'm puzzled when this class: https://github.com/fuel/core/blob/master/classes/date.php

Here are methods that I don't understand:

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

What is called first? What __counctruct does? What is factory, when it's used, what it returns - does it call itself again? Is _init called after initializing class? I'm really puzzled, can someone help me understand? Thanks

Was it helpful?

Solution

When an object is instantiated, the first method to be called is the __construct() method. This is called a constructor because it helps construct the class's data members and do any other initializing operations before you can call other methods int eh class.

A Factory is a creational design pattern used to create classes based on conditions that would not be known until runtime. - http://en.wikipedia.org/wiki/Factory_method_pattern

_init() seems to be another method that this library uses to set up it's classes.

To further your knowledge in these areas, i suggest you read up on OOP and then design patterns.

OTHER TIPS

This class looks like it is using the factory design pattern. Look it up here: PHP - Factory Design Pattern

The factory pattern allows you to instantiate a class at runtime. The _construct method runs as soon as the class is instantiated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top