I want to call a static method from one of my objects. This is no problem if I know the name of the object, but in this case, I don't.
I have an array with several object names and I want to call the method from one of this arrays elements. So, it looks something like this:
function call_method($key) {
$tmp = array('key1' => 'objectname1','key2' => 'objectname2','key3' => 'objectname3');
if(array_key_exists($key, $tmp)) {
$tmp::static_method();
}
}
But, this solution is not working. Does somebody know how to get this working?
$tmp
is an array, so it has no static methods associated with it. You need to look up the value and use that:
// this will work for newer versions of PHP
$klass = $tmp[$key];
$klass::static_method();
// in some older versions, you may need to use call_user_func:
call_user_func(array($klass, 'static_method') /*, your args here */);
Right now, you are trying to call the static function on that array. You should do :
if(array_key_exists($key, $tmp)) {
$tmp[$key]::static_method();
}
Thought you specified the names "object" in the array, I am assuming they are class names. Static functions cannot be called with instances.