【问题标题】:PHP Dynamic method calling inqueryPHP动态方法调用inquery
【发布时间】:2011-12-30 05:08:11
【问题描述】:

在复杂应用程序中创建了我自己的 MVC 框架后,我有一个问题。 我动态执行这样的函数:

<?php
class dyn {
  public function do_me() {
    echo "hello";
  }
  public function execute_other_method($var = 0) {
    if ($var != 0 && method_exists($this, $var)) {
      $this->$var();
    }
  }
}

$do_method = "do_me"; // this variable is usually from GET or POST, it's dynamically set anyway
$class = new dyn;
$class->execute_other_method($do_method); // echoes hello
?>

这完美无缺,但我的问题是:它有什么缺点吗?

如果我能改进这种执行方法,我很乐意这样做。

现在我在作为服务器的本地 PC 上执行复杂网页的平均时间为 0.0080s ~ 0.0150s,最大时间为 0.0300s(网页包括数据库查询、preg_match/replace、计算等)。

【问题讨论】:

    标签: php model-view-controller oop


    【解决方案1】:

    您有什么理由不使用 __get 方法吗?它的设计目的与您在上面所做的完全一样,只是您将调用而不是调用 execute_other_method,而是调用

    $class->do_me(); // this method exists and __get will call the method for you.
    

    $class->other_method(); // this method doesn't exist, but __get can handle it without throwing an error.
    

    那么您就不必将您的方法名称传递给另一个方法。

    【讨论】:

    • execute_other_method 不是在我的真实应用程序中执行其他功能的专用函数,在其中还有一些其他事情必须在执行该方法之前执行,例如检查用户是否是已登录,或者方法是否受到动态调用的保护(自定义保护,我不得不傻傻地证明它)。
    • 基本是这样的:function execute($code) { if (is_allowed($code) && is_custom($code) && !is_protected($code)){ $this->$code() ; } }
    • 您仍然可以使用 __get 方法做到这一点。请参阅:php.net/manual/en/language.oop5.overloading.php 了解更多详情。它只是为了让调用方法更简单、更直接。
    猜你喜欢
    • 2016-04-04
    • 2014-07-12
    • 2011-01-07
    • 2010-09-20
    • 2016-01-20
    • 2010-09-21
    • 2013-06-29
    相关资源
    最近更新 更多