奇怪的 php 方法调用

Strange php method call

我遇到了一种调用对象方法的奇怪方法。

$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 文件继承的变量。因此作为继承变量,它们是完全可访问的。

这里是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';

正如 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.

调用控制器操作的抽象方式