0
  • How to define constructor in Yii application?
  • Where ?to define the constructors?

I need to create constructors. Where it defines inside model or controller. Can you guys give some example of formats ?

2
  • There is a init() function you can use in models / controllers which will be executed on class call. Commented Apr 16, 2014 at 12:19
  • Yii's constructor call init() ?? Commented Apr 16, 2014 at 12:21

1 Answer 1

2

In a lot of Yii classes there are 2 methods that can be used to define initialization code : __construct() and init():

__construct() is a native php method to instantiate the object.

init() is called when Yii has performed it's own instantiation of the class (for example in a CActiveRecord class Yii has set the scenario name)

it's up to you to use

public function __construct()
{
    //Your code
    return parent::contruct()
}

or just to use the init method

public function init()
{
    //Your code
}

if you use construct be carefull because some classes constructors have some params that you'll also have to set (for example CActiveRecord take the scenario name as a param)

If I were you I'll use the init method as often as possible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.