-1

I want to call a static method from a variabe class in PHP. As pointed out several times on SO and because it is general practice, the following works as expected:

class Foo {
    public function compile($strClass) {
        $strClass::find(); // this works
    }
}

Nonetheless I have to call different find methods from $strClass from different methods of a class Foo. That is, why I want to store $strClass in $this->strClass. Unfortunately, this doesn't work:

class Foo {

    protected $strClass;

    public function __construct($strClass) 
    {
         $this->strClass = $strClass;
    }

    public function compile($strClass) {
        $this->strClass::find(); // this does not work
    }

}

Any idea or hint on how to solve that issue?

Update:

As pointed out in the comments, it might be a solution to use call_user_func like this:

call_user_func(array($this->strClass, 'find'), $strParam);

Anyhow, this makes code completion in PHPstorm impossible. Any hints on that? Maybe using code annotation?

Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
zinky
  • 151
  • 1
  • 1
  • 8
  • http://stackoverflow.com/a/3788003/2518525 – Darren Jul 22 '15 at 06:56
  • If `{$this->strClass}::find()` would work, how should PHPStorm code completion know the **runtime value** of `$this->strClass`? – Fabian Schmengler Jul 22 '15 at 07:44
  • I hope it was possible to tell PHPstorm that all classes, that might be stored in $this->strClass will have the same parent class, like e.g. /** @type Model $this->strClass */ (not working) – zinky Jul 22 '15 at 08:32

2 Answers2

1

You can change your compile method to this:

public function compile($strClass) {
    call_user_func(array($this->strClass, 'find'));
}
arbogastes
  • 1,308
  • 9
  • 10
0

This class design is flawed. I would try to get rid of the static methods completely, but here is a solution that exploits the fact that you can call static methods on objects:

class Foo {

    protected $strClass;

    public function __construct($strClass) 
    {
         $this->strClass = new $strClass;
    }

    public function compile($strClass) {
        $this->strClass::find();
    }

}

UPDATE: nevermind, this is a syntax error in all current PHP versions, you actually have to do it like this:

$strClass = $this->strClass;
$strClass::find();

And this works with your original code as well, where $this->strClass is a string.

Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111