15

In PHP you can call a class's static method from an object instance (which is contained in an array) like this:

$myArray['instanceOfMyClass']::staticMethod(); // works

But for some reason when I use the $this variable, I get a parsing error. E.g:

$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR

Just to illustrate what I mean:

class MyClass{
    public static function staticMethod(){ echo "staticMethod called\n"; }
}

$myArray = array();
$myArray['instanceOfMyClass'] = new MyClass;
$myArray['instanceOfMyClass']::staticMethod(); // works

class RunCode
{
    private $myArray;

    public function __construct(){
        $this->myArray = array();
        $this->myArray['instanceOfMyClass'] = new MyClass;
        $this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
    }
}

new RunCode;

Any ideas on how to get around this?

Mark
  • 2,669
  • 2
  • 17
  • 13
  • 1
    static = use self:: not $this-> – Waygood Jul 17 '12 at 09:09
  • Sorry? I don't think you get what I'm trying to do. I'm just trying to call a static method from an object instance of MyClass, which is an entry in RunCode->myArray. – Mark Jul 17 '12 at 09:19
  • 3
    use `call_user_func(array($this->myArray['instanceOfMyClass'], 'staticMethod'));` – Federkun Jul 17 '12 at 10:01

3 Answers3

16

You actually can use "->" to call static method:

$this->myArray['instanceOfMyClass']->staticMethod();
Eugene
  • 3,280
  • 21
  • 17
  • 1
    Oh wow, I never realised that thanks. So you can only use -> to call a static method if it's on an instantiated object? – Mark Jul 17 '12 at 10:49
  • Yes. It seems quite safe since you can't add a non-static method with same name to the class. – Eugene Jul 17 '12 at 11:06
  • Why does the PHP have to be this counter-intuitive? Anyway thanks fot the tip. – helvete Dec 09 '15 at 14:59
6

This is a really interesting problem, it may even be a bug in PHP itself.

For a work around, use the KISS principle.

class RunCode
{
    private $myArray;

    public function __construct(){
        $this->myArray = array();
        $this->myArray['instanceOfMyClass'] = new MyClass;

        $instance = $this->myArray['instanceOfMyClass']
        $instance::staticMethod();
    }
}

Hope this helps!

Sam Williams
  • 743
  • 1
  • 6
  • 15
  • Thanks, yeah I guess that is the most simple solution. My greatest pet peeve of PHP is the lack of support for syntax that you would just assume would work. E.g. $var = myFunction()[0]. Do you think this is worth filing a bug report about? – Mark Jul 17 '12 at 10:15
6

You will have to break up the one liner using a temporary variable, e.g.

$inst = $this->myArray['instanceOfMyClass'];
$inst::staticMethod()

This is one of many cases where PHP's compiler is not clever enough to understand nested expressions. The PHP devs have been improving this recently but there is still work to do.

Rich
  • 15,048
  • 2
  • 66
  • 119