首页 > 解决方案 > 将类自动加载到 PHP 交互式 Shell 中

问题描述

我试图Interactive shell从 php 脚本运行 php。更具体地说,我希望能够从交互式 shell 调用我的类。我设法找到这个

# custom_interactive_shell.php

function proc($command, &$return_var = null, array &$stderr_output = null)
{
    $return_var = null;
    $stderr_output = [];

    $descriptorspec = [
        // Must use php://stdin(out) in order to allow display of command output
        // and the user to interact with the process.
        0 => ['file', 'php://stdin', 'r'],
        1 => ['file', 'php://stdout', 'w'],
        2 => ['pipe', 'w'],
    ];

    $pipes = [];
    $process = @proc_open($command, $descriptorspec, $pipes);
    if (is_resource($process)) {
        // Loop on process until it exits normally.
        do {
            $status = proc_get_status($process);
            // If our stderr pipe has data, grab it for use later.
            if (!feof($pipes[2])) {
                // We're acting like passthru would and displaying errors as they come in.
                $error_line = fgets($pipes[2]);
                echo $error_line;
                $stderr_output[] = $error_line;
            }
        } while ($status['running']);
        // According to documentation, the exit code is only valid the first call
        // after a process is finished. We can't rely on the return value of
        // proc_close because proc_get_status will read the exit code first.
        $return_var = $status['exitcode'];
        proc_close($process);
    }
}

proc('php -a -d auto_prepend_file=./vendor/autoload.php');

但它只是不起作用,它试图进行交互但冻结了很多,即使在滞后之后它也没有真正正确地执行命令。

例子:

> php custom_interactive_shell.php
Interactive shell

php > echo 1;

Warning: Use of undefined constant eo - assumed 'eo' (this will throw an Error in a future version of PHP) in php shell code on line 1

标签: phpproc-open

解决方案


如果您希望能够从交互式 shell 运行您的 PHP 类,那么您可以使用终端附带的默认类。从终端输入: php -a

然后,在下面的示例中,我创建了一个名为 Agency.php 的文件,其中包含类 Agency。我能够将其 require_once() 放入活动 shell,然后调用该类及其方法:

Interactive shell

php > require_once('Agency.php');
php > $a = new Agency();
php > $a->setname("some random name");
php > echo $a->getname();
some random name

您还可以在交互式 shell 中使用以下内容来自动加载当前目录中的文件/类:

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

推荐阅读