繁体   English   中英

OOP中的动态方法调用

[英]Dynamic method call in OOP

我对 PHP 中的 OOP 编程没有太多经验,我的搜索没有给出任何结果,而是直接方法的解决方案。 我需要的是这个:

// URL Decides which controller method to load
$page = $_GET['page'];

// I want to load the correct controller method here
$this->$page();

// A method
public function home(){}

// Another method
public function about(){}

// e.g. ?page=home would call the home() method

编辑:我已经尝试了几个建议,但我得到的是 memory 过载错误消息。 这是我的完整代码:

<?php

class Controller {

    // Defines variables
    public $load;
    public $model;

    public function __construct() {

        // Instantiates necessary classes
        $this->load     = new Load();
        $this->model    = new Model();

        if (isset($_GET['page'])) {

            $page = $_GET['page'];

            $fc = new FrontController; // This is what crashes apparently, tried with and without ();

        }

    }

}

如果我正确理解你的问题,你可能想要更多这样的东西:

class FrontController {
    public function home(){ /* ... */ }
    public function about(){ /* ... */ }
}

$page = $_GET['page'];
$fc = new FrontController;
if( method_exists( $fc, $page ) ) {
    $fc->$page();
} else {
    /* method doesn't exist, handle your error */
}

这是你要找的吗? 该页面将查看传入的 $_GET['page'] 变量,并检查您的 FrontController class 是否具有名为 $_GET['page'] 的方法。 如果是这样,它将被调用; 否则,您需要对错误执行其他操作。

您可以使用以下方式调用动态属性和方法:

 $this->{$page}();

使用 class。

Class URLMethods {
  public function home(){ ... }
  public function about(){ ... }
}

$requestedPage = $_GET['page'];

$foo = new URLMethods();
$foo->$requestedPage();

您可以通过使用call_user_func来实现这一点。 另请参阅如何在 PHP 中动态调用 class 方法?

我想你也想 append 另一个字符串到这样的可调用函数:

public function homeAction(){}

为了防止黑客调用您可能不想使用的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM