【问题标题】:Autoloading Classes Into PHP Interactive Shell将类自动加载到 PHP 交互式 Shell 中
【发布时间】:2019-09-13 09:44:25
【问题描述】:

我正在尝试从 php 脚本运行 php Interactive shell。更具体地说,我希望能够从交互式 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

【问题讨论】:

    标签: php proc-open


    【解决方案1】:

    如果您希望能够从交互式外壳运行您的 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';
    });
    

    【讨论】:

      猜你喜欢
      • 2014-01-04
      • 2019-03-22
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多