php实现tinker
PHP 实现类似 Laravel Tinker 的功能
Laravel Tinker 是一个基于 PsySH 的 REPL(交互式解释器),允许在命令行中与 Laravel 应用交互。要在 PHP 中实现类似功能,可以借助 PsySH 或其他 REPL 工具。
安装 PsySH
通过 Composer 安装 PsySH:
composer require psy/psysh
基本实现
创建一个简单的 PHP 脚本加载 PsySH:

<?php
require __DIR__ . '/vendor/autoload.php';
$shell = new \Psy\Shell();
$shell->run();
集成 Laravel 环境
如果需要像 Laravel Tinker 那样访问 Laravel 服务容器:
<?php
require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();
$shell = new \Psy\Shell();
$shell->setScopeVariables(get_defined_vars());
$shell->run();
自定义配置
可以通过配置文件定制 PsySH 行为:

$config = new \Psy\Configuration([
'startupMessage' => '<info>Custom PHP Tinker</info>',
]);
$shell = new \Psy\Shell($config);
添加自定义命令
扩展 PsySH 的功能:
class MyCommand extends \Psy\Command\Command
{
protected function configure()
{
$this->setName('mycmd');
}
protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output)
{
$output->writeln('Custom command executed');
}
}
$shell->addCommands([new MyCommand()]);
运行方式
保存脚本为 tinker.php 后执行:
php tinker.php
替代方案
对于非 Laravel 项目,可以考虑:
- Boris:轻量级 PHP REPL
- PhpRepl:另一个 PHP 交互式解释器
- PHP 内置交互模式:
php -a






