首页 > 解决方案 > 苗条的路由和控制器(这个 __call 函数如何从路由调用以及为什么 $this->request 使用 $request= 的 insted)

问题描述

伙计们请帮我理解这些代码

在图 1 中,路由器使用 info 方法调用

正如您在 AccountController 中看到的那样,已经存在 info() 那么为什么 __call() 这个神奇的函数正在调用

这些参数是什么 $this->request ,$this->response

我们可以保存所有数据,例如

$request = $args[0]; $response = $args[1]; $attributes = $args[2];

为什么要使用 $this-> syntex 这条线的含义是什么 $this->$name();

路由器.php

<?php

$app->get('/account', '\App\Controller\AccountController:info');

?>

AccountController.php

<?php
/**
 * AccountController
 * @package Controllers
 */
namespace App\Controller;


final class AccountController extends \App\Core\Controller
{

    protected function info()
    {

        echo $this->client_id;

    }
}

控制器.php

 <?php

namespace App\Core;


 class Controller
{


  public function __call($name,$args) { //line 25
        //echo "Call method : ".$name;
        $this->request = $args[0];
        $this->response = $args[1];
        $this->attributes = $args[2];

        //print_r($this->attributes);
        $this->client_id = $this->request->getAttribute("client_id");



              $this->$name();

    }

}


?>

标签: phpoopcallslimmagic-function

解决方案


Router.phpinfo()在 AccountController.php 上调用了您的方法,但是您的方法受到保护,并且info()无法从类中访问该方法,因此使用和参数__call()调用了魔术方法。$name$args

$name => value 是方法名。“信息”。
$args => 响应、请求、属性的值数组

$this=> 它是对当前对象的引用,在面向对象的代码中最常用。 PHP 中的变量 $this 是什么意思?

request, response, attributes,client_id它们是控制器类的变量,可在控制器类子级的每个方法上访问。就像$this->client_id在你的AccountController课上一样。

    $this->request = $args[0];
    $this->response = $args[1];
    $this->attributes = $args[2];
    $this->client_id = $this->request->getAttribute("client_id");

$this->$name();这种调用方法的动态方式。

PHP 面向对象


推荐阅读