Skip to content

Magic variables

Justin Hileman edited this page Jul 23, 2017 · 4 revisions

✨ Magic variables

PsySH injects a number of magic variables into the session. You can use these just like you’d use any other variable.

Variable Value
$_ Last result
$_e Last exception
$__out Last stdout output
$__file Last file path
$__line Last line
$__dir Last directory path
$__class Last class name
$__method Last method name
$__function Last function name
$__namespace Last namespace name

Last result

The result of the latest (successful) execution is always available as $_, so you can use it in your next input.

>>> 10 + 11
=> 21
>>> $_ * 2
=> 42
>>> $_
=> 42

Last exception

The last uncaught error or exception is available as $_e.

>>> throw new Exception('wat')
Exception with message 'wat'
>>> $_e
=> Exception {#227
     #message: "wat",
     #file: "phar:///psysh/src/Psy/ExecutionLoop/Loop.php(90) : eval()'d code",
     #line: 1,
   }
>>>

You can also use the wtf command to view the latest exception’s backtrace, and show --ex to view the code which threw the exception.

To throw the most recent exception out of the current PsySH session, use the throw-up command.

Last stdout output

The stdout output from the last code executed is captured, and is available as $__out.

>>> echo "wat"
wat
>>> $__out
=> "wat"

Last file, line and directory

Some commands—such as doc, dump, ls, and show—set additional $__file, $__line and $__dir variables, as appropriate.

>>> show Psy\sh
  > 29|     function sh()
    30|     {
    31|         return 'extract(\Psy\Shell::debug(get_defined_vars(), isset($this) ? $this : null));';
    32|     }

>>> $__file
=> "/Projects/psysh/src/Psy/functions.php"
>>> $__line
=> 29
>>> $__dir
=> "/Projects/psysh/src/Psy"
>>>

These can be handy when combined with system shell integration.

Last namespace, class, method and function names

Some commands—such as doc and show—set additional $__namespace, $__class, $__method and $__function variables, as appropriate.

>>> show Psy\Shell::debug
  > 138|     public static function debug(array $vars = array(), $boundObject = null)
    139|     {
    140|         echo PHP_EOL;
    141|
    142|         $sh = new \Psy\Shell();
    143|         $sh->setScopeVariables($vars);
    144|
    145|         if ($boundObject !== null) {
    146|             $sh->setBoundObject($boundObject);
    147|         }
    148|
    149|         $sh->run();
    150|
    151|         return $sh->getScopeVariables(false);
    152|     }

>>> $__namespace
=> "Psy"
>>> $__class
=> "Psy\Shell"
>>> $__method
=> "Psy\Shell::debug"
>>> $__function
PHP error:  Undefined variable: __function on line 1
>>>