-1

I have an abstract class that contains the __construct method like this

abstract class Model
{
    protected $attributes = [];

    public function __construct(array $attributes = []) {
        $this->$attributes = $attributes;
    }
}

Then in my concrete class I extend the abstract Model

class Pong extends Model
{
    
}

When I dump the attributes inside the constructor I get an empty array, but if I remove the default value of the constructor parameter, the Pong model has attributes. The challenge is, I want to be able to construct the concrete class both with default values and without

$pong = new Pong();
$pong = new Pong(['msg' => 'Hello Kitty']);
kristian nissen
  • 2,809
  • 5
  • 44
  • 68

1 Answers1

-1

Give this a try:

I made the $attributes public, to show the results.

Note the question marks ??.

<?php

class Model
{
    public $attributes = [];

    public function __construct(array $attr = []) {
        $this->attributes['msg'] = $attr['msg'] ?? "default";
        $this->attributes['someValue'] = $attr['someValue'] ?? 'default';
    }
}

class Pong extends Model
{
    
}

$pong = new Pong();
print_r($pong->attributes);

Play around with the code you see above!

era-net
  • 387
  • 1
  • 11