Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor alternative for static methods in PHP

Tags:

php

static

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?

like image 546
Bart Jacobs Avatar asked Aug 22 '11 10:08

Bart Jacobs


People also ask

Can a constructor be static in PHP?

A static constructor is just a method the developer can define on a class which can be used to initialise any static properties, or to perform any actions that only need to be performed only once for the given class. The method is only called once as the class is needed.

Can static methods have constructors?

A static constructor doesn't take access modifiers or have parameters. A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR).

Can we override static method in PHP?

Here comes the call of static method with static keyword. In case there is no overridden function then it will call the function within the class as self keyword does. If the function is overridden then the static keyword will call the overridden function in the derived class.

What is new static () in PHP?

New static: The static is a keyword in PHP. Static in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on. The most common usage of static is for defining static methods.


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

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!

like image 52
Adi Ulici Avatar answered Oct 13 '22 00:10

Adi Ulici