0

I have two classes with the same static methods but each class has different implementation of the methods. In my code I know which static method I need to call, but the class type is determined dynamically. Something like this:

class someClass_A {
    public static function bar(){
        //some implementation;
    }
    public static function foo(){
        //some implementation;
    }
}

class someClass_B {
     public static function bar(){
        //different implementation;
    }
    public static function foo(){
        //different implementation;
    }
}

I am trying to use the in this manner:

$class = 'someClass_' . $indicator;
$bar = $class::bar();

But it's not working. Can I dynamically create a class name and then use it to call static function of that class?

user2395238
  • 850
  • 1
  • 9
  • 20

1 Answers1

0

You may use call_user_func_array for this.

class someClass_A {
    public static function bar() {
        return "I am the A-bar";
    }
    public static function foo() {
        return "I am the A-foo";
    }
}

class someClass_B {
    public static function bar() {
        return "I am the B-bar";
    }
    public static function foo() {
        return "I am the B-foo";
    }
}

$indicator = 'A';
$class = 'someClass_' . $indicator;
$aBar = call_user_func_array(array($class, 'bar'), array());

$indicator = 'B';
$class = 'someClass_' . $indicator;
$bFoo = call_user_func_array(array($class, 'foo'), array());

echo $aBar, PHP_EOL;
echo $bFoo, PHP_EOL;

Output:

I am the A-bar
I am the B-foo

Update

Then again, your code ...

$class = 'someClass_' . $indicator;
$aBar = $class::bar();

... actually should be working as well. Just remember to set the $indicator variable before calling:

$indicator = 'A';
$class = 'someClass_' . $indicator;
$aBar = $class::bar();
echo $aBar, PHP_EOL;

Output:

I am the A-bar
mhall
  • 3,671
  • 3
  • 23
  • 35