Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set object properties at constructor call time (PHP)

Tags:

php

I wonder if it's possible to achieve similar functionality to C#'s compact instantiation syntax:

itemView.Question = new ItemViewQuestion()
{
  AnswersJSON = itemView.Answer.ToJSONString(),
  Modified = DateTime.Now,
  ModifiedBy = User.Identity.Name
};

I wish to be able to create an object of arbitrary class passing their properties without having to set up constructor code for these properties.

To put up another example, this can be done with stdClass like this:

(object) ["name" => "X", "age" => 30]

Type juggling does not work for custom classes, however.

like image 310
Rápli András Avatar asked Dec 07 '25 02:12

Rápli András


1 Answers

There is no such functionality natively in PHP, unfortunately.

But you can create a class in your project and extend it in the classes you wish to instantiate without a constructor. Something like this:

<?php

class Fillable{
    public static function fill($props)
    {
        $cls = new static;
        foreach($props as $key=>$value){
            if (property_exists(static::class,$key)){
                $cls->$key = $value;
            }
        }
        return $cls;
    }
}
class Vegetable extends Fillable
{

    public $edible;
    public $color;
}

$veg = Vegetable::fill([
    'edible' => true,
    'color' => 'green',
    'name' => 'potato' //Will not get set as it's not a property of Vegetable. (you could also throw an error/warning here)
]);

var_dump($veg);

Checkout this fiddle for the working example

like image 171
Phiter Avatar answered Dec 08 '25 15:12

Phiter