rfc:class_properties_initialization

Request for Comments: Class properties initialization

Introduction

The purpose of this feature is to provide more advanced way to initialize class properties using closures, objects, type hinting.

Why do we need it?

  • code readability

Proposal

Main idea

class Foo
{
    private $var1 = function () { /* some callback ? */ }
 
    private $var2 = array ( 'foo' => function () { /* some callback ? */ } );
 
    private httpRequest $var3 = NULL;
}

instead of:

class Foo
{
    private $var1;
 
    private $var2;
 
    private $var3 = NULL;
 
    public function __construct ()
    {
        $this -> var1 = function () { /* some callback ? */ }
 
        $this -> var2 = array ( 'foo' => function () { /* some callback ? */ } );
 
        if ( ( $request = SomeCore :: getRequest () ) instanceof httpRequest )
        {
            $this -> var3 = $request;
        }
    }
}

Other / Related

* objects structures - structured objects initialization - like IoC/DI containers, where structure is not a result of code execution, but it's a result of strictly controlled design.

class Foo
{
    private $var1 = new Bar();
 
    private $var2 = Bar :: getInstance ();
}

* initialization with functions

class Foo
{
    private $var1 = time ();
 
    private httpRequest $var2 = getRequest ();
}

Rejected initialization types

private $foo = $this -> someStuff(); // impossible/nonsense (?)

Changelog

2010-07-30 k.antczak Initial RFC creation.

rfc/class_properties_initialization.txt · Last modified: 2017/09/22 13:28 by 127.0.0.1