[英]Dynamic method call in OOP
I don't have alot of experience with OOP programming in PHP, and my search has given no result but solutions to direct methods.我对 PHP 中的 OOP 编程没有太多经验,我的搜索没有给出任何结果,而是直接方法的解决方案。 What I need is this:
我需要的是这个:
// 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
EDIT: I've tried several of the suggestions, but what I get is a memory overload error message.编辑:我已经尝试了几个建议,但我得到的是 memory 过载错误消息。 Here is my full code:
这是我的完整代码:
<?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 ();
}
}
}
If I understand your question correctly, you'd probably want something more like this:如果我正确理解你的问题,你可能想要更多这样的东西:
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 */
}
Is this what you're looking for?这是你要找的吗? The page will look at the incoming $_GET['page'] variable, and check to see whether your FrontController class has a method named $_GET['page'].
该页面将查看传入的 $_GET['page'] 变量,并检查您的 FrontController class 是否具有名为 $_GET['page'] 的方法。 If so, it will be called;
如果是这样,它将被调用; otherwise, you'll need to do something else about the error.
否则,您需要对错误执行其他操作。
You can call dynamic properties and methods using something like this:您可以使用以下方式调用动态属性和方法:
$this->{$page}();
Use a class.使用 class。
Class URLMethods {
public function home(){ ... }
public function about(){ ... }
}
$requestedPage = $_GET['page'];
$foo = new URLMethods();
$foo->$requestedPage();
You can achieve this by using call_user_func .您可以通过使用call_user_func来实现这一点。 See also How do I dynamically invoke a class method in PHP?
另请参阅如何在 PHP 中动态调用 class 方法?
I think you'd like also to append another string to the callable functions like this:我想你也想 append 另一个字符串到这样的可调用函数:
public function homeAction(){}
in order to prevent a hacker to call methods that you probably don't want to be.为了防止黑客调用您可能不想使用的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.