Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set PHP class properties with construct() arguments automatically?

Does anyone know of an efficient technique in PHP to auto assign class parameters with identically named __construct() method arguments?

For instance, I've always thought it was highly inefficient to do something like the following:

<?php

class Foo
{
    protected $bar;
    protected $baz;

    public function __construct($bar, $baz)
    {
        $this->bar = $bar;
        $this->baz = $baz;
    }
}

I'm wondering if there's a better/more efficient way/magic method to auto-assign class properties with identically named method parameters.

Thanks,

Steve

like image 217
sstringer Avatar asked Jan 19 '26 10:01

sstringer


1 Answers

PHP 8

Constructor Promotion

function __construct(public $bar, public $baz) {}

PHP 5

function _promote(&$o) {
    $m = debug_backtrace(0, 2)[1];    
    $ref = new ReflectionMethod($m['class'], $m['function']);
    foreach($ref->getParameters() as $i=>$p) {
      $o->{$p->name} = $m['args'][$i] ?? $p->getDefaultValue();
    }
}

class Foo {
    function __construct($bar, $baz) {
        _promote($this);
    }
}
like image 186
Jehong Ahn Avatar answered Jan 22 '26 02:01

Jehong Ahn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!