Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

How would I get something like this to work?

$class_name = 'ClassPeer'; $class_name::doSomething(); 
like image 749
James Skidmore Avatar asked Jun 15 '09 19:06

James Skidmore


People also ask

Can you use a class name to call a static method?

Static methods have keyword "static" before the method name, belong to the class and not the instance, and can be accessed through the class name.

How do you call a static class from another class?

Call a static Method in Another Class in Java In the case of a static method, we don't need to create an object to call the method. We can call the static method by using the class name as we did in this example to call the getName() static method.

What happens if we call a method in a static method of the class?

If you try to call a static method via an instance you will get warning as you should avoid it, so you wont get a valid case but yes its logical to allow static call through instance.

Can I call a static method inside a regular one?

@Ian Dunn Put simply, $this only exists if an object has been instantiated and you can only use $this->method from within an existing object. If you have no object but just call a static method and in that method you want to call another static method in the same class, you have to use self:: .


1 Answers

Depending on version of PHP:

call_user_func(array($class_name, 'doSomething')); call_user_func($class_name .'::doSomething'); // >5.2.3 
like image 196
jimyi Avatar answered Oct 05 '22 07:10

jimyi