0

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

3 Answers 3

4
$obj = new $className();

$var = $className::method();
Sign up to request clarification or add additional context in comments.

Comments

3

1: $obj = new $className

2: $className::someMethod($parameter)

Comments

1

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";}
}

1 Comment

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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.