liysd
liysd

Reputation: 4613

how to create an object from given class name in php?

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

Upvotes: 0

Views: 444

Answers (3)

VolkerK
VolkerK

Reputation: 96159

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

Upvotes: 1

pauljwilliams
pauljwilliams

Reputation: 19225

1: $obj = new $className

2: $className::someMethod($parameter)

Upvotes: 3

Marcis
Marcis

Reputation: 4617

$obj = new $className();

$var = $className::method();

Upvotes: 4

Related Questions