Constructor Alternative for Static Methods in PHP

A few months ago, I read about a PHP function that is called every time a static method is called, similar to the function __constructthat is called when an instance of the class is created. However, I can’t find which function performs this function in PHP. Is there such a function?

+5
source share
3 answers

You can play with __ callStatic () and do something like this:

class testObj {
  public function __construct() {

  }

  public static function __callStatic($name, $arguments) {
    $name = substr($name, 1);

    if(method_exists("testObj", $name)) {
      echo "Calling static method '$name'<br/>";

      /**
       * You can write here any code you want to be run
       * before a static method is called
       */

      call_user_func_array(array("testObj", $name), $arguments);
    }
  }

  static public function test($n) {
    echo "n * n = " . ($n * $n);
  }
}

/**
 * This will go through the static 'constructor' and then call the method
 */
testObj::_test(20);

/**
 * This will go directly to the method
 */
testObj::test(20);

, , "_", "". , __callStatic, .

!

+6

__callStatic() , .

+3

Could __callStatic () be the method you are referring to? I just found this in the PHP Manual:

http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods

Perhaps not, however, since it seems like a magic method for handling undefined calls to static methods ...

+1
source

All Articles