【问题标题】:Closure scope issue: The script tried to execute a method or access a property of an incomplete object关闭范围问题:脚本试图执行方法或访问不完整对象的属性
【发布时间】:2021-03-29 17:51:09
【问题描述】:

我对以下代码有疑问。

<?php

include_once ('vendor/autoload.php');

use Spatie\Async\Pool;

$pool = Pool::create();

for($i = 0; $i < 100; $i++) {
    $task = new ExpensiveTask($i);
    $pool->add(function () use ($task) {
        return $task->delayedProcess();
    })->then(function ($output) {
        print "Completed task: " . $output;
    })->catch(function (Throwable $exception) {
        print $exception->getMessage();
    })->timeout(function () {
        print "timeout";
    });
}

$pool->wait();

class ExpensiveTask {

    private $taskId;

    public function __construct(int $index) 
   {
       $this->taskId = $index;
   }

   public function delayedProcess() {
       sleep(1);
       return $this->taskId;
   }
}

在执行上述代码时,我收到以下 500 错误。不知道为什么会这样。

PHP Fatal error:  {closure}(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "ExpensiveTask" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide an autoloader to load the class definition in closure://function () use ($task) {
        return $task->delayedProcess();
    } on line 3

如何解决这个问题,我是 PHP 闭包的新手。即使我尝试在使用它之前声明该类,但得到了同样的错误。

【问题讨论】:

    标签: php


    【解决方案1】:

    PHP 中的incomplete Object 通常只是一个(还)不存在的类。注意声明和实例化类对象的顺序。

    将你的类声明移到你的执行代码之上,你应该没问题。

    编辑

    即使我尝试在使用它之前声明该类,但得到相同的错误。

    不过,上述情况仍然成立。在 99.9% 的情况下,这是您的声明/执行命令。

    编辑 2

    根据您的回答:在您的自定义类之前加载的自动加载器文件未添加到自动加载器类映射中。所以答案仍然成立。课程确实加载得太晚了。

    【讨论】:

    • 我向上帝发誓我做到了,但仍然遇到同样的错误。看来这件事很严重。
    • @Unnikrishnan 查看编辑。
    【解决方案2】:

    在作曲家自动加载中添加了类并且工作正常。

    "autoload": {
        "files": ["src/ExpensiveTask.php"]
    }
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 2014-01-06
      • 2012-02-02
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多