How To Create Object Or To Use Static Methods Of Any Class?

What is the way to create object of class or to use its static methods if I know path to class?

For example I have class with name someClass in @app\myfolder\someClass.php. What I have to do?

And second question. What I have to do if I know namespace of class?

1 Like

If root namespace is \app then:

// instance

$object = new \app\myfolder\SomeClass();


// static method



use \app\myfolder\SomeClass;

// instance

$object = new SomeClass();


// static method



when u have this coding in your main.php file…

// autoloading model and component classes





Default you will have those classes automatically…

There’s no need to do any import in Yii2.

If I want to store path to class what I must do?

class myclass extends Object


public $class='\app\myfolder\SomeClass';


You will just have to get used to type a bit more with namespaces in Yii2. Don’t try to shorthand everything. This particular thing you are trying to get an answer for cannot be done. Correct usage is as described above.

I have found what I must do:


	$myclass = new $string;


Ok. I catch the correct way. But what about aliases? If I have alias ‘@app/folder/myclass’ only what I have to do to create object?

And what I have to do to use static method of my class?


namespace app\folder;

class myclass


	public function echoit()


		echo 'You have done it';


	public static function staticMethod()


		echo 'It is static method';



Is the correct way?


        $string::staticMethod(); //Is it correct?

Yes. It is correct.

I have a little investigation about namespaces and aliases in Yii2.

To use class we can use namespaces style.

For static:



		$result = call_user_func([$myclass, $mymethod]);

For non-static:



		$object=new $myclass;


But I think we can’t autoload and use classes if we use aliases like @app/folder/myclass.


what will happen to the following code?

use \app\folder_a\SameNameClass;

use \app\folder_b\SameNameClass;

$obj = new SameNameClass();//which class will be used to create the instance?

PHP doesn’t allow this. You have to alias one of the classes to be something different.

got you, qiang! :lol: :lol: :lol:

thank you for answer, and very glad to meet you! I love the Yii framework and I am using it in my work, it is really great! hope you guys keep doing the great job.

btw, a happy thanks giving day to you and the yii team(maybe a little late…) !

Now I’ve found out how use static methods of any class. But I have another question. How to use static property of any class in Yii2?

Any suggestions?

Same way as in PHP.

I’ve made another tests


namespace app\folder;

class myclass


	public static $myvar=2013;

	public static function getMyVar()


		return 'Your var is ' . self::$myvar;



In controller we can do:


		echo $myclass::getMyVar(); //For static methods

		echo '<br />';

		echo $myclass::$myvar; //For static properties

Thanks to Pathfinder and samdark.