Take an example from the documentation :

namespace app\models; use yii\db\ActiveRecord; class User extends ActiveRecord { const SCENARIO_LOGIN = 'login'; const SCENARIO_REGISTER = 'register'; public function scenarios() { return [ self::SCENARIO_LOGIN => ['username', 'password'], self::SCENARIO_REGISTER => ['username', 'email', 'password'], ]; } } 

In the example above, the scripts are defined as constants:

 const SCENARIO_LOGIN = 'login'; const SCENARIO_REGISTER = 'register'; 

We initialize them in one of the following ways:

 // scenario is set as a property $model = new User; $model->scenario = User::SCENARIO_LOGIN; // scenario is set through configuration $model = new User(['scenario' => User::SCENARIO_LOGIN]); 

Question

Why not do so ...

Scenarios are defined as regular strings:

 namespace app\models; use yii\db\ActiveRecord; class User extends ActiveRecord { public function scenarios() { return [ 'login' => ['username', 'password'], 'register' => ['username', 'email', 'password'], ]; } } 

We initialize them accordingly:

 // scenario is set as a property $model = new User; $model->scenario = 'login'; // scenario is set through configuration $model = new User(['scenario' => 'login'); 

    1 answer 1

    Strings are difficult to analyze and refactor.

    While you have 10 files, you can safely use the find-replace if you want to rename something. You will not forget where what values ​​are used and why (if not a year has passed). If you have 1000 files, the "login" line can be used in dozens of places in dozens of different values. If you want to change all the values ​​or just find all the uses you need, then you will have problems.

    In the case of the use of constants and a normal development environment, you can at any time rename anything to anything or use the search for uses of a constant.

    In addition, constants protect against typos. Without constants, if you are sealed up in a certain place, you will be wondering for a long time what went wrong.

    • one
      I’ll add from the documentation (regarding events, but it doesn’t matter): It is recommended to use class constants to represent event names. ... This approach has three benefits. First, it prevents typos. Second, it can make events recognizable for IDE auto-completion support. Third, you can tell what events are supported in a class by simply checking its constant declarations. . - Roman Grinyov