Why do some php classes have an empty init () method?

For example, in a Yii2 structure, a Class yii\filters\AccessControloverrides a function init()from its parent class yii\base\Object. This Object class in turn has a constructor such as this:

    Class Object implements Configurable {
        public function __construct($config = [])
        {
            if (!empty($config)) {
                Yii::configure($this, $config);
        }
        $this->init(); // calls the method defined below
        }
    }
// and the definition of this init function ... 
    public function init()
    {
    }

Now there is no explicit use of writing such an empty function if you do not want to use some properties that may be needed in the future for initialization.

But then the method __construct()has exactly the same meaning! I need to understand how this method init()is useful.

+4
source share
2 answers

The reason is simple: they expect class expansion

So you would do something like this

class Bob extends Object {
    public function init() {
        $this->setup_something();
    }
}

Bob extends Object, Bob - , . -, defintion, .

- :

class Bob extends Object {
    public function __construct($config = []) {
         $this->setup_something();
    }
}

, - , - ( ): ( , parent::__construct($config)). , init(), . .

+5

Yii . Yii:

init() - (, , ).

init() , . , . init(), , , , . .

init() , , . , CApplication preInit() init(). , .

, . , Yii, init() , , .

- . Yii init() . init(). , , . , init(), . , , .

+3
source

Source: https://habr.com/ru/post/1623761/


All Articles