forsvunnet
forsvunnet

Reputation: 1258

Can static methods be called as a public method?

I wrote a small test scenario for testing mixed use of static and non-static methods. When calling a public method as a static method it generates a strict warning. That got me thinking that perhaps calling a static method as a public method would generate a similar warning, but it did not.

Is it ok to call static methods as a non-static method? Are there any consequences to doing so?

<?php
class TestS {
  static function _testS() {
    echo("Hello Static<br>\n");
    // Strict warning: Non-static method TestS::_tS() should not be
    // called statically in TestS::_tS()
    self::_tS();
  }
  public function _tS() {
    echo("tS<br>\n");
  }
  public function _testP() {
    echo("Hello Public<br>\n");
    self::_tP();
  }
  static function _tP() {
    echo("tP<br>\n");
  }
  public function _testSP() {
    $this->_tP();
  }
}

$test = new TestS();
echo("///////////<br>\n");
$test->_testP();
echo("///////////<br>\n");
TestS::_testS();
echo("///////////<br>\n");
$test->_testSP();
echo("///////////<br>\n");

Upvotes: 1

Views: 125

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173642

Is it ok to call static methods as a public method?

Theoretically, it is. That's because a static method doesn't reference $this anywhere, so it will work when called either statically or as an instance method.

Are there any consequences to doing so?

It's a good practice to indicate explicitly what kind of method you're calling; when looking back on your code you will know exactly which method is static because of the way you're calling it, with the notable exception of using parent::method() inside an instance method.

It's also a good practice to avoid using static methods in the first place; if you have a lot of them, it's often indicates a code smell and should be refactored.

Upvotes: 1

Related Questions