[英]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.