2

in Python, you could do something like this:

class SomeClass(object): pass
s = SomeClass
someClassInstance = s()

How could you accomplish the same effect in PHP? From what I understand, you cannot do this? Is this true?

Pwnna
  • 9,178
  • 21
  • 65
  • 91

2 Answers2

7

You can create instances of dynamic class names; simply pass the name of the class as a string:

class SomeClass {}
$s = 'SomeClass';
$someClassInstance = new $s();
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • If you're that paranoid, get a computer that runs PHP 5.2 and run it yourself. (You did it in the last 3 hours since posting that comment, I'm sure?) – BoltClock May 31 '11 at 16:37
  • School blocks FTP. Can't go into my php 5.2 test server ATM, which is why I asked :P – Pwnna May 31 '11 at 18:14
  • Well, that bites. So did mine :/ – BoltClock May 31 '11 at 18:15
  • Sometimes school blocks the most senseless thing. This website was once blocked. I don't have anywhere saying that this doesn't work under PHP 5.2. – Pwnna May 31 '11 at 18:16
  • @ultimatebuster, the comment http://www.php.net/manual/en/language.variables.variable.php#98641 suggests that it works on 5.2. – Matthew May 31 '11 at 19:26
1

Using reflection:

class SomeClass {}
$s = new ReflectionClass('SomeClass');
$someClassInstance = $s->newInstance();

The nice thing about using reflection is that it throws a catchable exception in the event the class does not exist.

Matthew
  • 47,584
  • 11
  • 86
  • 98