指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

php之first_class_callable_syntax的使用:

  • 声明一个Test类
<?php

namespace App\Controller\Admin;

use Closure;

/**
 * 声明一个Test类
 */
class Test {
    public function getPrivateMethod(): Closure
    {
        return Closure::fromCallable([$this, 'privateMethod']); //8.1之前
        //return $this->privateMethod(...);//8.1之后
    }

    private function privateMethod(): void
    {
        file_put_contents('./3.txt', __METHOD__.time());
    }
}
  • 在这个控制器里 调用 Test类
<?php

namespace App\Controller\Admin;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;


/**
 * 在这个控制器里 调用 Test类
 */
class IndexController extends AbstractController
{
    #[Route('/admin', name: 'admin')]
    public function index(Request $request): Response
    {
        // 初始化类
        $test = new Test;
        // 调用类里的私有化方法,得到一个Closure
        $privateMethod = $test->getPrivateMethod();
        // 执行这个 Closure
        $privateMethod();

        return $this->renderForm('admin/index.html.twig');
    }
}

参考(https://wiki.php.net/rfc/first_class_callable_syntax)

各个版本的PHP的wiki(https://wiki.php.net/rfc#php_83)
RFC解释:request for comments(征求意见),应该是php的社区版