Jump to content

[SOLVED] How do I call a static method from an unknown class?


Recommended Posts

Hi,

I have a strange problem, but I really need to figure out how this works.

 

abstract class A
{
  function A() { echo "constr. A"; }
  static abstract function foo();
}

class B extends A
{
  function B() { echo "constr. B"; }
  static function foo() { echo "B::foo"; }
}

class C extends A
{
  function C() { echo "constr. C"; }
  static function foo() { echo "C::foo"; }
}

function getClName()
{
  return C;
}

$clname = getClName();
// $obj = new $clname(); // this would work
$clname::foo(); // this does not work! how can I make this work?

 

I think you can see my problem. I want to call a static method of a class I don't know. It works perfectly when constructing an object and calling its non-static methods. But how can I call its static methods without creating an object from it?

 

greetings, Salim

You can use the new object construction as zanus suggested and just use the -> operator, as long as you don't put the static keyword in front of your method declaration. PHP is lenient on calling functions statically. You can call any function using the static member operator :: and it'll work up until a $this reference. That gets a little awkward though, and you've already used the static keyword.

 

Another way would be to look at call_user_func() and see how you can format callback:

mixed call_user_func  ( callback $function  [, mixed $parameter  [, mixed $...  ]] )

function - The function to be called. Class methods may also be invoked statically using this function by passing array($classname, $methodname) to this parameter.

So in this context:

$class=getClName(); //Returns a string "C"
call_user_func(array($class,"foo")); //Calls C::foo()

You can add whatever parameters you want. Also look at call_user_func_array() if you want some more flexiblity.

 

EDIT: Fixed the error Anthop pointed out. Otherwise it would have executed C("foo") instead of C::foo().

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.