开发者

Instantiate a new class with the value of a string

开发者 https://www.devze.com 2022-12-12 20:29 出处:网络
This might be a very stupid question :P But I found this really interessting: class SomeClass{ var $var = \"this is some text\";

This might be a very stupid question :P But I found this really interessting:

class SomeClass{

var $var = "this is some text";

function echoVar($name){
  echo $this->{$name};
}
}
$class = new SomeClass()
$class->echoVar("var") // will echo "this is some text"

Can I do so开发者_JAVA百科methign similar, can I take the value of a string and instantiate a new class with that name? If not, any "almost" solutions?

Thanks


Yes. You can dynamically instantiate classes in PHP. Like this:

$className = 'SomeClass';
$myInstance = new $className();


If your string 'dave' is in $name, you can use it with $$name

$name = 'dave';
$$name = new SomeClass();
$dave->echoVar('var');
0

精彩评论

暂无评论...
验证码 换一张
取 消