OOP中的动态方法调用

时间:2011-07-19 17:05:40

标签: php 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
编辑:我已经尝试了几个建议,但我得到的是内存过载错误消息。这是我的完整代码:

<?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 ();

        }

    }

}

4 个答案:

答案 0 :(得分:3)

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

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类是否有一个名为$ _GET ['page']的方法。如果是这样,它将被调用;否则,你需要对错误做些其他事情。

答案 1 :(得分:0)

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

 $this->{$page}();

答案 2 :(得分:0)

使用课程。

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

$requestedPage = $_GET['page'];

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

答案 3 :(得分:-1)

您可以使用call_user_func来实现此目的。另请参阅How do I dynamically invoke a class method in PHP?

我认为您还想将另一个字符串附加到可调用函数,如下所示:

public function homeAction(){}

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