views:

27

answers:

3

I have a variable $className which is name of declared class in php and I want

  1. create an object of this class
  2. lunch a static method of this class
+4  A: 
$obj = new $className();

$var = $className::method();
Anpher
+3  A: 

1: $obj = new $className

2: $className::someMethod($parameter)

Visage
+1  A: 

There's also the Reflection API. E.g.:

<?php
$rc = new ReflectionClass('A');
// question 1) create an instance of A
$someArgs = array(1,2,3);
$obj = $rc->newInstanceArgs($someArgs);

// question 2) invoke static method of class A
$rm = $rc->getMethod('foo');
if ( !$rm->isStatic() ) {
  echo 'not a static method';
}
else {
  $rm->invokeArgs(null, $someArgs);
}

class A {
  public function __construct($a, $b, $c) { echo "__construct($a,$b,$c)\n";}
  public static function foo($a, $b, $c) { echo "foo($a,$b,$c)\n";}
}
VolkerK
oh, I didn't expect this one to be accepted. Keep in mind that IMO there's nothing wrong with `new $className()` if it fits your needs. ReflectionClass lets you do more stuff but it also adds some complexity.
VolkerK
I accepted your answer becouse in my editor $className::method() is marked as an error...
liysd