Skip to main content
 首页 » 编程设计

php之函数的神奇函数 __call()

2025年12月25日89kenshinobiy

php 中的神奇函数 __call() 在类中使用。除了函数之外,还有类似的神奇函数吗?就像 __autoload() 用于函数一样。

例如这样的事情

function __call($name, $arguments) { 
    echo "Function $name says {$arguments[0]} "; 
} 
random_func("hello"); 

请您参考如下方法:

不,我不认为存在这样的神奇功能。

解决此问题的一种方法是将函数放入静态类中,并添加 __callStatic该类的魔术方法(恐怕仅适用于 PHP 5.3):

class Func 
 { 
   /**  As of PHP 5.3.0  */ 
   public static function __callStatic($name, $arguments) 
     { 
    // Note: value of $name is case sensitive. 
    echo "Calling static method '$name' " 
         . implode(', ', $arguments). "\n"; 
 
  } 
 } 
 
Func::random_func("hello!"); 

对于 PHP < 5.3,您可以执行相同的操作,但您必须实例化一个对象并使用 __call 魔术方法。

$Func = new Func; 
$Func->random_func("hello!");