This is an old revision of the document!

PHP RFC: Code free constructor


“Code free” constructor is constructor with only purpose to directly set object properties from received parameters and, optionally, call parent constructor.

They used for:

  • for DTO-classes declaration
  • developers, that believe it is good OOP-practice, use them everywhere
  • useful in some cases of inheritance

Unfortunately, php syntax enforces to write unnecessary boilerplate.


Proposal is to add alternate syntax for “code free” constructors.

Current syntax:

class MotorCycle {
    public $vendor;
    public $cc;
    public $whells = 2;
    public function __construct($vendor, $cc) {
        $this->vendor = $vendor;
        $this->cc     = $cc;
    //other methods
class MyCustomMotorCycle extends MotorCycle {
    public function __construct($cc, $whells) {
     // $this->cc = $cc;  this statement will be added within proposed realisation
        $this->whells = $whells;
        parent::__construct("Custom", $cc);

Proposed syntax:

class MotorCycle($vendor, $cc){
    //other methods
class MyCustomMotorCycle($cc, $whells) extends MotorCycle("Custom", $cc){ };

Possible Issue

Child constructor will rewrite parent's properties with same name.

class Parent{
    public function __construct($prop){
        $this->prop = $prop * 2;
class Child($prop) extends Parent($prop) {};
$child = new Child(5);
object(Child) {
    ["prop"] => 5 // instead expected 10

Backward Incompatible Changes

Do not know. Looks like no BI.

Proposed PHP Version(s)

PHP 8.x

RFC Impact

Not thinking so

Future Scope


Implemented via injecting generated “__construct”'s ast node into class statements list. So it will be compiled with all checks.

Draft implementation, need to be reviewed. https://github.com/rjhdby/php-src/tree/constructor


rfc/code_free_constructor.1547729159.txt.gz · Last modified: 2019/01/17 12:45 by rjhdby