Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中静态方法的构造函数替代方案_Php_Static - Fatal编程技术网

PHP中静态方法的构造函数替代方案

PHP中静态方法的构造函数替代方案,php,static,Php,Static,几个月前,我读过一篇关于每次调用静态方法时都会调用的PHP函数的文章,类似于实例化类实例时调用的\u construct函数。然而,在PHP中,我似乎找不到哪个函数负责这个功能。有这样一个函数吗?您所指的方法是u callStatic()吗?我刚在PHP手册中找到: 也许不是,因为它似乎是处理未定义静态方法调用的神奇方法…每次调用类的非现有静态方法时都会调用u callStatic() 你可以玩这样的游戏: class testObj { public function __constru

几个月前,我读过一篇关于每次调用静态方法时都会调用的PHP函数的文章,类似于实例化类实例时调用的
\u construct
函数。然而,在PHP中,我似乎找不到哪个函数负责这个功能。有这样一个函数吗?

您所指的方法是u callStatic()吗?我刚在PHP手册中找到:

也许不是,因为它似乎是处理未定义静态方法调用的神奇方法…

每次调用类的非现有静态方法时都会调用u callStatic()

你可以玩这样的游戏:

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);
类testObj{ 公共函数构造(){ } 公共静态函数\uuu callStatic($name,$arguments){ $name=substr($name,1); 如果(方法_存在(“testObj”,$name)){ echo“调用静态方法'$name'
”; /** *您可以在这里编写任何要运行的代码 *在调用静态方法之前 */ 调用_user_func_数组(数组(“testObj”,$name),$arguments); } } 静态公共功能测试($n){ echo“n*n=”.($n*$n); } } /** *这将通过静态“构造函数”,然后调用该方法 */ testObj::_测试(20); /** *这将直接转到方法 */ testObj::test(20); 使用此代码,任何前面带有“\u1”的方法都将首先运行静态“构造函数”。 这只是一个基本的示例,但是您可以使用
\uu callStatic
,但是它对您的效果更好


祝你好运

不久前,我在PHP手册中偶然发现了这个方法,但是,正如您所提到的,只有在调用不存在的静态方法时才会调用它。我恐怕这不是我正在寻找的方法。谢谢你的回复。这不是我所希望的,但我认为这是最接近我想要的。谢谢,Adi。致命错误:在第30行调用未定义的方法testObj::\u test()