John Smith
John Smith

Reputation: 6197

Responsibility of constructor, how much may it does?

I want know if a constructor can do "deeped" things, of just initializing. Consider this:

class Entity
{
    private $data;

    public function __construct(array $datasAlready)
    {
        $this->json_encode($datasAlready);
    }
}

exising a Entity is pointless if no $data was filled. This way, I enforce load this. But my boss told its not okay, constructor ideally would only do basic inicializations, so:

class Entity
{
    private $data;

    public function __construct(array $datasAlready)
    {
        $this->data = array();
    }

    public function load(array $datasAlready)
    {
        $this->json_encode($datasAlready);
    }
}

or even constructor is not needed. But this way I miss the enforcing of initialization. What if I start using this object when not filled?

Upvotes: 0

Views: 41

Answers (1)

rjhdby
rjhdby

Reputation: 1387

Constructor almost like normal function and you can do anything inside it. But it's not best practics.

If you don't describe constructor in class, will be used default empty constructor.

Upvotes: 1

Related Questions