fork download
  1. <?php
  2.  
  3. class Fillable{
  4. public static function fill($props)
  5. {
  6. $cls = new static;
  7. foreach($props as $key=>$value){
  8. if (property_exists(static::class,$key)){
  9. $cls->$key = $value;
  10. }
  11. }
  12. return $cls;
  13. }
  14. }
  15. class Vegetable extends Fillable
  16. {
  17.  
  18. public $edible;
  19. public $color;
  20. }
  21.  
  22. $veg = Vegetable::fill([
  23. 'edible' => true,
  24. 'color' => 'green',
  25. 'name' => 'potato' //Will not get set as it's not a property of Vegetable. (you could also throw an error/warning here)
  26. ]);
  27.  
  28. var_dump($veg);
Success #stdin #stdout 0s 82880KB
stdin
Standard input is empty
stdout
object(Vegetable)#1 (2) {
  ["edible"]=>
  bool(true)
  ["color"]=>
  string(5) "green"
}