1

Am trying to run php Interactive shell from a php script. To be more specific, I want to be able to call my classes from interactive shell. I manage to find this

# 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');

But its just not working, it tries to be interactive but freezes up a lot, and even after the lag it doesn't really execute commands properly.

Example:

> 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
Ghostff
  • 1,407
  • 3
  • 18
  • 30

1 Answers1

1

If you want to be able to run your PHP classes from an interactive shell then you can use the default one that ships with Terminal. From the terminal just type: php -a

Then, in the below example I had created a file called Agency.php that had class Agency in it. I was able to require_once() it into the active shell and then call the class and its methods:

Interactive shell

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

You can also use the following in the interactive shell to autoload the files / classes in the current directory:

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});
Risteard
  • 318
  • 2
  • 12