6

A few months ago, I have read about a PHP function that is called every time a static method is called, similar to the __construct function that is called when an instance of class is instantiated. However, I can't seem to find what function takes care of this functionality in PHP. Is there such a function?

3 Answers 3

7

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);

Using this code any method that is preceded by '_' will run the static 'constructor' first. This is just a basic example, but you can use __callStatic however it works better for you.

Good luck!

Sign up to request clarification or add additional context in comments.

2 Comments

It's not what I hoped for, but I think it's the closest to what I am looking for. Thanks, Adi.
Fatal error: Call to undefined method testObj::_test() on line 30 codepad.org/Go96TaaS
3

The __callStatic() is called everytime you call not existing static method of a class.

1 Comment

I stumbled upon this method in the PHP manual some time ago, but, as you mention, it is only called when a non-existing static method is called.
1

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, though, since it seems to be a magic method to handle undefined static method calls...

1 Comment

I'm afraid this is not the method I am looking for. Thanks for your reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.