函数的神奇函数 __call() ?

发布于 2024-09-13 10:35:18 字数 226 浏览 8 评论 0原文

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

例如这样的事情

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

The magic function __call() in php are used in classes. Are there any similar magic function but for functions instead? Like __autoload() is for functions.

For example something like this

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七月上 2024-09-20 10:35:18

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

解决此问题的一种方法是将函数放入静态类中,并添加 __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!");

Nope, I don't think such a magic function exists.

One workaround for this would be to put your functions into a static class, and add a __callStatic magic method to that class (> PHP 5.3 only, I'm afraid):

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

For PHP < 5.3, you could do the same thing, but you would have to instantiate an object and use the __call magic method.

$Func = new Func;
$Func->random_func("hello!");
深府石板幽径 2024-09-20 10:35:18

不可以。调用不存在的函数总是会导致致命错误。

** 也许 zend 扩展可以使用 fcall_begin_handler 拦截此行为,但我不确定。

No. Calling a function that doesn't exist will always result in a FATAL error.

** Maybe a zend extension can intercept this with a fcall_begin_handler, but I'm not sure.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文