我面对一种奇怪的方法来调用对象上的方法。
$controller->{ $action }();
但是如果我删除花括号,那么无论如何调用都会有效。有人知道那些花括号是什么意思吗?
<?php
function call($controller, $action) {
// require the file that matches the controller name
require_once('controllers/' . $controller . '_controller.php');
// create a new instance of the needed controller
switch($controller) {
case 'pages':
$controller = new PagesController();
break;
}
// call the action
$controller->{ $action }();
}
// just a list of the controllers we have and their actions
// we consider those "allowed" values
$controllers = array('pages' => ['home', 'error']);
// check that the requested controller and action are both allowed
// if someone tries to access something else he will be redirected to the error action of the pages controller
if (array_key_exists($controller, $controllers)) {
if (in_array($action, $controllers[$controller])) {
call($controller, $action);
} else {
call('pages', 'error');
}
} else {
call('pages', 'error');
}
?>
$ controller和$ action是从index.php文件继承的变量,需要这个变量。因此,作为继承变量,它们是完全可访问的。
// set default controller and action
$controller = 'login';
$action = 'index';
// check if $_GET variables are set
if(isset($_GET['controller']) && $_GET['action'])
{
// if we have something set in here we override the default value
$controller = $_GET['controller'];
$controller = $_GET['action'];
}
// now we require the router file who will read the $controller and $action vars.
require_once '../app/core/Router.php';
答案 0 :(得分:3)
当Dagon链接到您时,该示例中的方法名称为variable variable。
如果您只是单独使用变量名,则不需要大括号,但是如果您想将字符串连接到变量名,那么您需要大括号,例如:
// These are the same:
$controller->$action();
$controller->{$action}();
// This won't work:
$controller->custom$action();
// This will work:
$controller->{'custom' . $action}();
示例中的 $action
表示方法名称,例如Run
,因此您可以运行$controller->customRun()
。
在您的上下文中,它是一种基于提供$controller
和$action
来调用控制器操作的抽象方式。