Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Classes load() method good/bad practice?

Tags:

oop

php

Just wondering if you could shed some light on best practices?

Would having a load method in a Class be the correct/best way?

Class Test extends Foo{

    public $id;
    public $name;

    public function __construct()
    {
        parent::__construct();

    }

    public function load($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}

Or would it be concidered better practice to just have the load method logic in the constructor?

Class Test extends Foo{

    public $id;
    public $name;

    public function __construct($id, $name)
    {
        parent::__construct();

        $this->id = $id;
        $this->name = $name;
    }
}

The 2nd option seems to be more logical to me as it's one less method and it's called automatically etc, however, I've seen the 1st option more often. Is there a reason for this? Any help would be appreciated!

like image 628
Rwd Avatar asked Apr 11 '26 01:04

Rwd


1 Answers

The second option is best. A constructor is meant to prepare the object for use. It is the perfect place to initialize properties etc. Unless you have a good reason for using load() instead of the constructor, go with the second example.

like image 191
Wayne Whitty Avatar answered Apr 13 '26 14:04

Wayne Whitty



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!