【问题标题】:Strange php method call奇怪的php方法调用
【发布时间】:2016-05-02 07:00:25
【问题描述】:

我正面临一种调用对象方法的奇怪方式。

$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';

【问题讨论】:

标签: php oop model-view-controller methods function-call


【解决方案1】:

正如 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-&gt;customRun()

在您的上下文中,这是一种基于提供$controller$action 调用控制器操作的抽象方式。

【讨论】:

  • 但是在这种情况下使用这种类型的调用是否值得?
  • 绝对 - 这是常见的做法,您只需要在调用之前验证该操作是否存在
  • @Caius 永远不要删除其中的$controller-&gt; 部分,运行{ $action }(); 之类的代码可能非常危险。
  • @cmorrissey 你为什么要这样做?肯定会破坏控制器系统
  • @cmorrissey 为什么我必须从 {$action}(); 中删除 $controller-> ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 2014-12-09
相关资源
最近更新 更多