2011-07-19 38 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