How to Create __construct or init()

Hi,guys,I’m using Yii2.0 php-5.6 Centos6.4

I wanna use __construct() or init() in my custom class,but error happend.

Here is Controller code.


<?php


namespace frontend\modules\yiitest\controllers;

use yii\web\Controller;


class ApiController extends Controller

{                                                                    

    public function actions()

    {

        return [

            'apitest' => 'frontend\modules\yiitest\MyTestAction',

        ];

    }

}



And the action code.




namespace  frontend\modules\yiitest;

use frontend\modules\yiitest;

use yii\base\Action;


class MyTestAction extends Action

{

    public function run()

    {

        $params =  \Yii::$app->request->post();

        $data = yiitest\testMyClass::execute($params);

        print_r($data);die;

    }                                                         

}



My custom class code testMyClass.




namespace frontend\modules\yiitest;

use frontend\modules\yiitest\util;

use yii\base\Object;


class testMyClass extends Object

{


private $obj;

public function init()   //__contstruct() has the same problem

{

    parent::init();

    $this->obj = new util\common; 

}


public function execute($params)

{

    $this->obj->run($params['id']);

}



And error code like this.




Unknown Property – yii\base\UnknownPropertyException


Getting unknown property: frontend\modules\yiitest\MyTestAction::obj



Thanks for any feedback.

Try instantiating "testMyClass" before you execute.




  $params =  \Yii::$app->request->post();

  $test = new yiitest\testMyClass();

  $data = $test->execute($params);

  print_r($data);die;



execute doesn’t return anything, by the way.

Thank you ,It worked :)

I made a terriable mistake.

Don’t worry, there’s ways to deal with that: https://en.wikipedia.org/wiki/Seppuku