【问题标题】:Migrate to PHP 8.0: Unbinding $this when $this is used迁移到 PHP 8.0:使用 $this 时取消绑定 $this
【发布时间】:2021-05-07 22:05:19
【问题描述】:

我正在逐步将我的项目从 PHP 7.1 迁移到 PHP 8.0

在 PHP 官方手册中,在 “从 PHP 7.3.x 迁移到 PHP 7.4.x”一章的子章节 “弃用的功能” 中,我尝试了了解以下deprecation description

在使用$this 时取消绑定$this

取消绑定使用$this 的非静态闭包的$this 已弃用。

虽然没有成功。

这就是为什么我会很感激,如果有人可以详细解释我,这意味着什么。也许代码 sn-p 也会有所帮助。

非常感谢您的宝贵时间!


也许这也有助于解释

在我的项目中,我认为只有一种情况适用此弃用通知:适用于下面介绍的RouteCollection 类的方法executeGroupHandler。为了帮助您了解我使用方法executeGroupHandler 的上下文,我更愿意粘贴更多该类的代码。

RouteCollection 类:

<?php

namespace Packages\Router;

//...
use Packages\Router\RouteCollectionInterface;


/**
 * Route collection.
 */
class RouteCollection implements RouteCollectionInterface {

    //...

    /**
     * Group patterns list. Indexed array.
     *
     * Each time a group handler is executed its pattern is saved in this list.
     * All addRoute operations taken place inside the scope of a group handler
     * prefix the pattern of the corresponding route with the saved group pattern.
     *
     * @var array
     */
    private $groupPatterns = [];

    //...

    /**
     * Add a group (helper method).
     *
     * @param string $pattern Group pattern.
     * @param \Closure $handler Group handler.
     * @return $this
     */
    public function group(string $pattern, \Closure $handler) {
        $this->addGroup($pattern, $handler);
        return $this;
    }

    /**
     * Add a group.
     *
     * @param string $pattern Group pattern.
     * @param \Closure $handler Group handler.
     * @return $this
     */
    private function addGroup(string $pattern, \Closure $handler) {
        $this->saveGroupPattern($pattern);

        $this->executeGroupHandler($handler);

        /*
         * Remove the last group pattern from the group patterns list. This step
         * is performed only after all calls for adding groups/routes inside the
         * scope of the current group handler have finished their processing.
         */
        $this->popLastGroupPattern();

        return $this;
    }

    /**
     * Save a group pattern.
     *
     * @param string $pattern Group pattern.
     * @return $this
     */
    private function saveGroupPattern(string $pattern) {
        $this->groupPatterns[] = $pattern;
        return $this;
    }

    /**
     * Execute a group handler.
     *
     * Temporarily bind the group handler to the route collection 
     * object - defined by the argument in Closure::call - and 
     * execute it. Inside the scope of the group handler, the route 
     * collection will be accessed using the keyword "$this".
     * 
     * @link https://www.php.net/manual/en/closure.call.php Closure::call
     *
     * @param \Closure $handler Group handler.
     * @return mixed The return value of calling the handler.
     */
    private function executeGroupHandler(\Closure $handler) {
        return $handler->call($this);
    }

    /**
     * Pop the group pattern off the end of group patterns list.
     *
     * @return string The popped group pattern.
     */
    private function popLastGroupPattern() {
        return array_pop($this->groupPatterns);
    }

}

RouteCollection 类的使用:

定义了RouteCollection 类,我使用它类似于以下内容:

<?php

use Packages\Router\RouteCollection;
use SampleMvc\App\View\Template\Users\AddUser as AddUserView;
use SampleMvc\App\Controller\Users\AddUser as AddUserController;

$routeCollection = new RouteCollection();

// Add a group of routes to the route collection.
$routeCollection->group('/users/add', function() {
    $this->get('', [AddUserView::class, 'index']);

    $this->post('', [
        'controller' => AddUserController::class,
        'view' => [AddUserView::class, 'addUser'],
    ]);
});

//...

【问题讨论】:

    标签: php php-7 php-7.4 php-8


    【解决方案1】:

    弃用的是 proposed (and accepted) in this RFC,它提供了有关弃用的内容和原因的更多详细信息。

    最后一句解释了哪些闭包受到影响:

    这尤其适用于在非静态方法中声明的非静态闭包。通过将闭包标记为静态,可以首先避免 $this 绑定。

    后来进一步缩小了in this commit,因此它仅适用于闭包中实际提到$this的闭包。

    同时,第一句话给出了一个更清晰的例子,说明 what 被弃用了:

    目前可以通过使用$closure-&gt;bindTo(null) 将$this 变量与最初有一个闭包的闭包解除绑定。

    关键字是 unbind 而不是 rebind,以及示例中的 null

    还有来自 Nikita in this comment 的更多背景资料:

    我们对此弃用感兴趣的原因仅仅是为了在 PHP 8 中启用与 $this 访问相关的一些性能改进,这是通过删除对非静态方法的静态调用来实现的。 $this 访问可以分为两类:我们知道 $this 是非空的和我们不知道的。方法调用(将)属于前一类。随着这种弃用,闭包也将属于前一类。

    换句话说,在 PHP 8 中,引擎会盲目地假设闭包中对 $this 的任何引用实际上都是一个对象,而不是 null。

    因此,不推荐使用的特定场景是您有一个提到$this 的闭包,然后您取消绑定它,因此$this 根本没有设置任何东西。只要您为$this 提供新值,您就不会受到影响,因为$this 永远不会是null

    【讨论】:

    • 谢谢你,IMSop。
    【解决方案2】:

    问得好,我也不明白 PHP 中“解除绑定的闭包变量”是什么意思。

    我写了一个简单的测试来检查绑定另一个$this是否可以被认为是“解除绑定$this”:

    class ClosureTest extends TestCase
    {
    
        private $x = 1;
    
        public function testClosure(): void
        {
            var_dump(\PHP_VERSION);
            $callable = function (): int {
                return $this->x;
            };
            self::assertSame(1, \call_user_func($callable));
    
            $closure = \Closure::fromCallable($callable);
    
            $obj = new class {
                private $x = 2;
            };
            self::assertSame(2, $closure->call($obj));
        }
    }
    
    

    我在 7.3 和 8.0 下都运行过它并且没有收到任何通知,因此您的代码可能在 8.0 下也可以安全运行。但我会进一步调查这个问题。

    【讨论】:

    • 谢谢你的回答,爱德华。有趣的方法。实际上,我刚刚意识到,……一个非常有趣的!
    猜你喜欢
    • 2011-04-24
    • 2020-01-15
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多