2

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 somethign similar, can I take the value of a string and instantiate a new class with that name? If not, any "almost" solutions?

Thanks

2 Answers 2

4

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

$className = 'SomeClass';
$myInstance = new $className();
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

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