Method for getting a class from a string

Is there a way to get an instance of a class (in my case, an ActiveRecord) from simply a string of the class name.

My class name is “Person”, and I’m wondering if there’s a reflection method in Yii that allows me to do this?

What do you mean? New instance of the class? Like $person = new Person;?

Yes. However I only have a string "Person" that tells me the kind of class I want to instantiate.

I get that it’s possible to just do this:


if ($string ==  "Person") {Person = new Person;}

However, I’m wondering if it’s possible to use some sort of reflection within Yii to instantiate an instance of person using only that string. So, a method like:


instantiateClassByName($string)

Am I making that clear?

You could do something like




$modelNameString = '//frontend//models//Person';

$model = new $modelNameString();



or something like




$nameSpace ='//frontend//models//';

!$string ==="Person"?:new $nameSpace.$string();



You have to include the full path or it won’t know what model to use. You have to use double slashes to escape the path too.

You do realise that you can do this?




$string = "Person";

$object = new $string;



I just tried it and it didn’t work for me without the complete namespace unless you include the use statement at the top of the page.But if it’s dynamic then you won’t really know what it is…for example i have models in common and in frontend/backend.

Well of course you have to use namespace. For every instance of class inheriting Object class you can use static method className() that returns fully qualified name of the class.

Yep, agreed… on a side note @bizley the ajaxdropdown widget you made is a pretty cool… nicely done. I have never seen it until now.

Cheers!