PHP Function Return New Object

Through our years of programming, we have optimized and re-optimized our code in attempt to make things easier for us, and to reduce redundant code.

During our endeavours, we implemented an abstract class containing a function that returns a new object instance:

abstract class i_object {
    final public static function i() {
        return count(func_get_args()) ? call_user_func_array(array(new static, '__construct'), func_get_args()) : new static;
    }
}

You can then create your business logic class like this:

class user extends i_object {
    public $id;
    function __construct($id = null, $populate = false) {
        $this->id = $id;
        if ($populate)
            $this->populate();
        return $this; // * important
    }
    function populate() {
        // populate from db
    }
}

Then, when you want to create a new “user” object:

$user = user::i($id, true);

We check for arguments in i_object::i(), so the object is then instantiated with those same params.

* It is imperative that you return $this; in the __construct function of the class extending the abstract class.  If omitted, nothing will be returned when calling ::i().

1 thought on “PHP Function Return New Object

Leave a Reply

Your email address will not be published. Required fields are marked *