2011-07-19 39 views
-1

我在PHP中使用OOP编程方面没有太多的经验,而且我的搜索没有给出任何结果,而是直接方法的解决方案。我需要的是这样的: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(); 

     } 

    } 

} 
+2

你试过了吗? – netcoder

回答

0

可以调用使用像这样的动态属性和方法:

$this->{$page}(); 
0

使用类。

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

$requestedPage = $_GET['page']; 

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

但允许url变量来控制流是一个可怕的想法,由于安全等原因。如果你打算通过这个,确保你清理(显式检查允许的值)的GET变量。 –

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

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

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

public function homeAction(){} 

,以防止黑客打电话,你可能不希望方法。

+0

为什么不把这种方法变为私有? – Ryan

+0

以防万一您需要从另一个班级调用该方法。无论如何,你的评论问题是主观的,这是ZendFramework实际执行的方式,所以我认为这样做确实有一些逻辑。 – s3v3n

+0

并且自从什么时候额外的安全性毫无意义? – s3v3n