Dmitry Minkovsky
Dmitry Minkovsky

Reputation: 38173

Parse error when calling a static method on an object that's referenced by an instance property

Here's my test:

<?php

require __DIR__ . '/vendor/autoload.php';

class HasStatic {
  public static function static_method() {
    return true;
  }
}

class SUT {
  public $has_static;

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

  public function call_static() {
    // A parse error :<
    // $this->has_static::static_method();
    $has_static = $this->has_static;
    return $has_static::static_method();
  }

}

class PhpStaticCallOnProperty extends PHPUnit_Framework_TestCase {
  public function testPhpStaticCallOnProperty() {
    $sut = new SUT();
    $this->assertTrue($sut->call_static(), 'call_static() succeeded');
  }
} 

As you can see, I discovered that $this->has_static::static_method(); yields a parse error.

Is there a clean way to make this call without the extra assignment?

Upvotes: 1

Views: 397

Answers (1)

George Brighton
George Brighton

Reputation: 5151

Static methods are black boxes of functionality where you explicitly define everything going in (parameters) and out (return value). As such, they are not tied to an object - and you shouldn't call them using an object reference. static_method() should only ever be called using HasStatic::static_method(), or self::static_method() from within the HasStatic class.

There's nothing inherently wrong with static methods - I strongly disagree with tereško saying they should be avoided. If a method doesn't need an object's context, it may as well be static.

The parse error occurs because there's no reason to use the scope resolution operator (::) on a property. Variable class names do mean the following will work:

$foo = 'HasStatic';
$foo::static_method(); // equivalent to HasStatic::static_method()

However that variable cannot be a property - you'll have to assign it to a temporary variable if you want to call the method in this way.

Upvotes: 1

Related Questions