Skip to content

Instantly share code, notes, and snippets.

@ramen
Created May 4, 2011 22:21
Show Gist options
  • Save ramen/956167 to your computer and use it in GitHub Desktop.
Save ramen/956167 to your computer and use it in GitHub Desktop.
PHP command line interface
#!/usr/bin/env php
<?php // -*- php -*-
print("PHP version " . phpversion() . " on " . PHP_OS);
print(" (use Ctrl-D to exit)\n");
if (function_exists('pcntl_signal')) {
pcntl_signal(SIGINT, SIG_IGN);
}
if (!function_exists('readline')) {
function readline($prompt) {
fputs(STDOUT, $prompt);
$s = fgets(STDIN);
return $s === false ? false : rtrim($s);
}
}
if (!function_exists('readline_add_history')) {
function readline_add_history($line) {}
}
if (function_exists('readline_completion_function')) {
readline_completion_function('repl_complete');
}
function repl_complete($str, $idx) {
$result = array();
if (strlen($str)) {
foreach ($GLOBALS as $name => $val) {
$result[] = $name;
}
foreach (get_declared_classes() as $name) {
$result[] = $name;
}
foreach (get_declared_interfaces() as $name) {
$result[] = $name;
}
foreach (get_defined_constants() as $name => $val) {
$result[] = $name;
}
foreach (get_defined_functions() as $type => $arr) {
foreach ($arr as $name) {
if (strpos($name, $str) !== false) {
$result[] = $name;
}
}
}
}
return $result;
}
function repl_code_has_block($code) {
$tokens = token_get_all("<?php $code");
foreach ($tokens as $token) {
if ($token == '{') {
return true;
}
}
return false;
}
while (true) {
$_line = readline('php?> ');
if ($_line === false) {
echo "\n";
break;
}
if (strlen($_line) && !repl_code_has_block($_line)) {
readline_add_history($_line);
$_line = rtrim($_line, ';');
eval("print_r(\$_ = $_line);");
print("\n");
} else {
$_lines = array();
while (strlen($_line)) {
readline_add_history($_line);
$_lines[] = $_line;
$_line = readline(' ');
}
if ($_lines) {
$_ = eval(implode("\n", $_lines));
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment