为什么方法实例化后包含$this->info("")的方法会报错?

1. 运行环境

1). 当前使用的 Laravel 版本?

6.20.39

2). 当前使用的 php/php-fpm 版本?

PHP 版本:7.4

2. 问题描述?

在laravel框架的Commands里创建命令行脚本,代码如下:

namespace App\Console\Commands;


use Illuminate\Console\Command;

class Test2 extends Command
{
    protected $signature = 'test2';
    protected $description = '测试方法2';

    public function __construct()
    {
        parent::__construct();
    }
    public function handle(){

        $this->info("hello");
    }
}

此时的执行结果是成功的:

# php artisan test2
hello

可是在其他类中实例化引用,$this->info关联方法就会出现问题:

namespace  App\Console\Commands; 
use  Illuminate\Console\Command; 

class  Test  extends  Command  {
    protected $signature = 'test';
    protected $description = '测试方法';

    public function __construct()
    {
      parent::__construct();
    }

    public function handle()
    {
      $t = new Test2();
      $t->handle();
    }
}
  # php artisan test

   Symfony\Component\Debug\Exception\FatalThrowableError  : Call to a member function writeln() on null

  at /www/vendor/laravel/framework/src/Illuminate/Console/Concerns/InteractsWithIO.php:264
    260|     public function line($string, $style = null, $verbosity = null)
    261|     {
    262|         $styled = $style ? "<$style>$string</$style>" : $string;
    263| 
  > 264|         $this->output->writeln($styled, $this->parseVerbosity($verbosity));
    265|     }
    266| 
    267|     /**
    268|      * Write a string as comment output.

  Exception trace:

  1   Illuminate\Console\Command::line("hello", "info")
      /www/vendor/laravel/framework/src/Illuminate/Console/Concerns/InteractsWithIO.php:249

  2   Illuminate\Console\Command::info("hello")
      /www/app/Console/Commands/Test2.php:25

  Please use the argument -v to see more details.

测试后发现,只要包含$this->info(“”); 相关打印,脚本就会停止。
不明白这是为什么

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

这样

    use Symfony\Component\Console\Output\ConsoleOutput;

    public function __construct()
    {
        parent::__construct();
        $this->output = new ConsoleOutput;
        $this->info("hello");
    }
2年前 评论
right-chen (楼主) 2年前
讨论数量: 8

你这个测试有问题吧,都递归调用了,没有溢出也是厉害的

2年前 评论
right-chen (楼主) 2年前
陈先生

你猜你new出来的那个类的 output 属性是个什么?

2年前 评论

这样

    use Symfony\Component\Console\Output\ConsoleOutput;

    public function __construct()
    {
        parent::__construct();
        $this->output = new ConsoleOutput;
        $this->info("hello");
    }
2年前 评论
right-chen (楼主) 2年前

应该是this指向的问题,你把两个的this都打印一下

2年前 评论

Test2继承的Command类里有一个方法run(),laravel执行handle()时会先用run()方法初始化output,所以比较合理的方式是不要自己去实例化,应该使用Artisan::call('test2');这样的方式调用其他命令

参考Artisan 命令行

2年前 评论
right-chen (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!