How can I call a static method from a class if all I have is a string of the class name?

Php

Php Problem Overview


How would I get something like this to work?

$class_name = 'ClassPeer';
$class_name::doSomething();

Php Solutions


Solution 1 - Php

Depending on version of PHP:

call_user_func(array($class_name, 'doSomething'));
call_user_func($class_name .'::doSomething'); // >5.2.3

Solution 2 - Php

To unleash the power of IDE autocomplete and error detection, use this:

$class_name = 'ClassPeer';

$r = new \ReflectionClass($class_name );

// @param ClassPeer $instance

$instance =  $r->newInstanceWithoutConstructor();

//$class_name->doSomething();
$instance->doSomething();

Basically here we are calling the static method on an instance of the class.

Solution 3 - Php

Use call_user_func. Also read up on PHP callbacks.

call_user_func(array($class_name, 'doSomething'), $arguments);

Solution 4 - Php

After I have almost missed the simplest solution from VolkerK, I have decided to extend and put it in a post. This is how to call the static members on the instance class

// calling class static method
$className = get_class($this);
$result = $className::caluclate($arg1, $arg2);

// using class static member
foreach ($className::$fields as $field) {
  :
}

Solution 5 - Php

Reflection (PHP 5 supports it) is how you'd do this. Read that page and you should be able to figure out how to invoke the function like that.

$func = new ReflectionFunction('somefunction');
$func->invoke();

Documentation Link

Solution 6 - Php

These answers are all outdated:

<?php

class MyTest{
	
	public static function bippo(){
		echo "hello";
	}
}

$a = MyTest::class;
$a::bippo();

works fine

Solution 7 - Php

if you need to adjust the namespace

$call = call_user_func(array('\\App\\Models\\'.$class_name, "doSomething"));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames SkidmoreView Question on Stackoverflow
Solution 1 - PhpjimyiView Answer on Stackoverflow
Solution 2 - PhpDavid GarciaView Answer on Stackoverflow
Solution 3 - PhpTJ LView Answer on Stackoverflow
Solution 4 - PhpMaxZoomView Answer on Stackoverflow
Solution 5 - PhpapanditView Answer on Stackoverflow
Solution 6 - PhpToskanView Answer on Stackoverflow
Solution 7 - PhpMauro LacerdaView Answer on Stackoverflow