Skip to main content
The main PsySH Shell class. This is the core REPL (Read-Eval-Print-Loop) application.

Constructor

__construct(?Configuration $config = null)

Create a new Psy Shell instance.
config
Configuration
Configuration instance. If not provided, a default Configuration will be created.
use Psy\Shell;
use Psy\Configuration;

// Create shell with default config
$shell = new Shell();

// Create shell with custom config
$config = new Configuration(['colorMode' => 'forced']);
$shell = new Shell($config);

Public Methods

run(?InputInterface $input = null, ?OutputInterface $output = null): int

Run the PsySH REPL.
input
InputInterface
Symfony Console input instance (optional)
output
OutputInterface
Symfony Console output instance (optional)
return
int
Exit code (0 on success)
$shell = new Shell();
$exitCode = $shell->run();

boot(?InputInterface $input = null, ?OutputInterface $output = null): void

Boot the shell, initializing the CodeCleaner and Readline. This is called lazily when commands or methods require these dependencies.
input
InputInterface
Input for trust prompts (optional)
output
OutputInterface
Output for trust prompts (optional)
$shell = new Shell();
$shell->boot();

execute(string $code, bool $throwExceptions = false): mixed

Execute code in the shell execution context.
code
string
required
PHP code to execute
throwExceptions
bool
default:"false"
Whether to throw exceptions instead of catching them
return
mixed
The result of the executed code
$shell = new Shell();
$result = $shell->execute('return 2 + 2;');
// $result === 4

addCommand(BaseCommand|callable $command): ?BaseCommand

Add a command to the shell.
command
BaseCommand|callable
required
A Symfony Console Command object or callable
return
BaseCommand|null
The registered command, or null
use Symfony\Component\Console\Command\Command;

$shell = new Shell();
$shell->addCommand(new MyCustomCommand());

setScopeVariables(array $vars): void

Set the variables currently in scope.
vars
array
required
Associative array of variable names to values
$shell = new Shell();
$shell->setScopeVariables([
    'foo' => 'bar',
    'items' => [1, 2, 3],
]);

getScopeVariables(bool $includeBoundObject = true): array

Return the set of variables currently in scope.
includeBoundObject
bool
default:"true"
Pass false to exclude ‘this’. If you’re passing the scope variables to extract() you must exclude ‘this’.
return
array
Associative array of scope variables
$shell = new Shell();
$vars = $shell->getScopeVariables();
$varsWithoutThis = $shell->getScopeVariables(false);

getScopeVariable(string $name): mixed

Get a scope variable value by name.
name
string
required
Variable name (without $)
return
mixed
Variable value
$shell = new Shell();
$shell->setScopeVariables(['foo' => 'bar']);
$value = $shell->getScopeVariable('foo'); // 'bar'

setBoundObject($boundObject): void

Set the bound object ($this variable) for the interactive shell.
boundObject
object|null
required
Object to bind as $this in the shell
class MyClass {
    private $secret = 'hidden';
}

$obj = new MyClass();
$shell = new Shell();
$shell->setBoundObject($obj);
// Now you can access $this->secret in the shell

getBoundObject(): ?object

Get the bound object ($this variable) for the interactive shell.
return
object|null
The bound object, or null

setBoundClass($boundClass): void

Set the bound class (self) for the interactive shell.
boundClass
string|null
required
Fully qualified class name to bind as self
$shell = new Shell();
$shell->setBoundClass('App\\MyClass');
// Now you can access static members via self:: in the shell

getBoundClass(): ?string

Get the bound class (self) for the interactive shell.
return
string|null
The bound class name, or null

setIncludes(array $includes = []): void

Add includes to be parsed and executed before running the interactive shell.
includes
array
default:"[]"
Array of file paths to include
$shell = new Shell();
$shell->setIncludes([
    '/path/to/bootstrap.php',
    '/path/to/helpers.php',
]);

getIncludes(): array

Get PHP files to be parsed and executed before running the interactive shell.
return
string[]
Array of file paths

addMatchers(array $matchers): void

Add tab completion matchers.
matchers
array
required
Array of matcher instances
use Psy\TabCompletion\Matcher\ClassNamesMatcher;

$shell = new Shell();
$shell->addMatchers([new ClassNamesMatcher()]);

setOutput(OutputInterface $output): void

Set the shell output.
output
OutputInterface
required
Symfony Console output instance

setForceReload(bool $force): void

Enable or disable force-reload mode for code reloaders. Used by the yolo command to bypass safety warnings when reloading code.
force
bool
required
Whether to force reload

hasCode(): bool

Check whether this shell’s code buffer contains code.
return
bool
True if the code buffer contains code

addCode(string $code, bool $silent = false): void

Add code to the code buffer.
code
string
required
PHP code to add
silent
bool
default:"false"
Whether to add silently (won’t appear in history)
$shell = new Shell();
$shell->addCode('$x = 1;');
$shell->addCode('$y = 2;');

getCodeBuffer(): array

Get the current code buffer. This is useful for commands which manipulate the buffer.
return
string[]
Array of code lines in the buffer

resetCodeBuffer(): void

Reset the current code buffer. This should be run after evaluating user input, catching exceptions, or on demand by commands.

flushCode(): ?string

Flush the current (valid) code buffer. If the code buffer is valid, resets the code buffer and returns the current code.
return
string|null
PHP code buffer contents, or null if invalid

addInput($input, bool $silent = false): void

Inject input into the input buffer. This is useful for commands which want to replay history.
input
string|array
required
Input line(s) to inject
silent
bool
default:"false"
Whether to add silently

getNamespace(): ?string

Get the current evaluation scope namespace.
return
string|null
Current code namespace, or null
$shell = new Shell();
$shell->addCode('namespace App\\Controllers;');
$namespace = $shell->getNamespace(); // 'App\\Controllers'

writeStdout(string $out, int $phase = PHP_OUTPUT_HANDLER_END): string

Write a string to stdout. This is used by the shell loop for rendering output from evaluated code.
out
string
required
Output to write
phase
int
default:"PHP_OUTPUT_HANDLER_END"
Output buffering phase
return
string
Empty string

writeReturnValue($ret, bool $rawOutput = false): void

Write a return value to stdout. The return value is formatted or pretty-printed, and rendered in a visibly distinct manner.
ret
mixed
required
Return value to write
rawOutput
bool
default:"false"
Write raw var_export-style values

writeException(Throwable $e): void

Render and write a caught exception or error. Exceptions are formatted according to severity. Stores the exception as the last exception in the shell context.
e
Throwable
required
Exception or error instance to write

getLastExecSuccess(): bool

Check whether the last execution was successful. Returns true if a return value was logged rather than an exception.
return
bool
True if last execution was successful

formatException(Throwable $e): string

Helper for formatting an exception or error for writeException().
e
Throwable
required
Exception to format
return
string
Formatted exception message

handleError(int $errno, string $errstr, string $errfile, int $errline): void

Error handler for throwing ErrorExceptions. This respects error levels and the errorLoggingLevel config.
errno
int
required
Error type
errstr
string
required
Error message
errfile
string
required
Filename where error occurred
errline
int
required
Line number where error occurred

Static Methods

isIncluded(array $trace): bool

Check whether the first thing in a backtrace is an include call. This is used by the psysh bin to decide whether to start a shell on boot, or to simply autoload the library.
trace
array
required
Backtrace array from debug_backtrace()
return
bool
True if the trace shows an include

isPhar(): bool

Check if the currently running PsySH bin is a phar archive.
return
bool
True if running from a phar

getVersionHeader(bool $useUnicode = false): string

Get a pretty header including the current version of PsySH.
useUnicode
bool
default:"false"
Whether to use Unicode characters
return
string
Version header string
echo Shell::getVersionHeader(true);
// Psy Shell v0.12.20 (PHP 8.2.0 — cli)

Constants

VERSION
string
Current PsySH version number (e.g., ‘v0.12.20’)

Usage Example

use Psy\Shell;
use Psy\Configuration;

// Create a shell with custom configuration
$config = new Configuration([
    'colorMode' => 'forced',
    'startupMessage' => 'Welcome to my app!',
]);

$shell = new Shell($config);

// Set up context
$shell->setScopeVariables([
    'app' => $myApp,
    'db' => $database,
]);

// Bind an object context
$shell->setBoundObject($myObject);

// Add files to include on startup
$shell->setIncludes([
    __DIR__ . '/bootstrap.php',
]);

// Execute some code
$result = $shell->execute('return app()->version();');

// Start interactive REPL
$exitCode = $shell->run();

Build docs developers (and LLMs) love