CodeIgniter Forums
What are the differences among initialize(), constructor and early options? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: What are the differences among initialize(), constructor and early options? (/showthread.php?tid=81138)



What are the differences among initialize(), constructor and early options? - castle - 01-27-2022

Hi,
Sorry if the title is confusing, but looking at the documentation I got wondering. How are they different?
PHP Code:
class UserModel extends UserAuthModel
{
    /**
    * Called during initialization. Appends
    * our custom field to the module's model.
    */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }

PHP Code:
class UserModel extends UserAuthModel
{
    protected $allowedFields 'middlename';

PHP Code:
class UserModel extends UserAuthModel
{
    public function __construct()
    {
        $this->allowedFields[] = 'middlename';
    }

Don't they all execute the code first thing when the class is initiated?
Thanks


RE: What are the differences among initialize(), constructor and early options? - kenjis - 01-27-2022

This is wrong usage. The model does not work fine. See the BaseModel::__constuct().

PHP Code:
class UserModel extends UserAuthModel
{
    public function __construct()
    {
        $this->allowedFields[] = 'middlename';
    }


The initialize() is a method called at the end of the constructor.
You can write initialization code in it.


RE: What are the differences among initialize(), constructor and early options? - kilishan - 01-27-2022

The intent of the initialize method in the Controller was solely to free up the constructor for your own usage as a developer without having to worry about the class dependencies. My advise - use class vars or the constructor and ignore the initialize method whenever possible.