2

Are there any howtos for using the PHP command line interactively?

I found a lot about running scripts that are in text files, but not really about the shell with the prompt where I type in commands:

$ php -a
Interactive shell

php > echo "hello world";
hello world
php > $a = 1;
php > echo $a;
1
php > exit;
$

When I go to the Linux shell and run php -a I get the PHP shell. Can I load classes that live in files? What are the rules here?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user89021
  • 14,784
  • 16
  • 53
  • 65

6 Answers6

5

Instructions to install phpsh in Ubuntu 10.04 Server edition.

Get phpsh source and extract

  wget http://github.com/facebook/phpsh/zipball/master

  sudo apt-get install unzip

  mkdir temp

  mv facebook-phpsh-8438f3f.zip temp

  cd temp

  unzip facebook-phpsh-8438f3f.zip

phpsh uses python, install dependencies

  sudo apt-get install python-setuptools

  sudo apt-get install linux-headers-$(uname -r)

  sudo apt-get install build-essential

  sudo apt-get install python-dev

  sudo apt-get install sqlite3 libsqlite3-dev

  sudo easy_install pysqlite

  sudo apt-get install libncurses5-dev

  sudo easy_install readline

Setup phpsh, run and see that is works

  sudo python setup.py install

  phpsh

    $a = array("a"=>1,"b"=>2);

    print_r($a)
mozey
  • 2,222
  • 2
  • 27
  • 34
3

The rules aren't any different to a normal PHP script - just think of it like reading from a very slow disk... The only real difference is that it can't read ahead, so you have to define functions before you use them.

You can use include or require as normal to load classes.

Greg
  • 316,276
  • 54
  • 369
  • 333
2

The interactive mode for php is somewhat limited. You may find phpsh more useful.

troelskn
  • 115,121
  • 27
  • 131
  • 155
1

I believe you can use include. You can include files relative to the location you called the command.

KahWee Teng
  • 13,658
  • 3
  • 21
  • 21
1

There is another minor difference that could be problematic if you rely on the class-autoloading-behavior of PHP:

Note: Autoloading is not available if using PHP in CLI interactive mode.

Source: Using PHP from the command line and Autoloading Objects

Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
0

Use Boris

Python has one. Ruby has one. Clojure has one. Now PHP has one too. Boris is PHP's missing REPL (read-eval-print loop), allowing developers to experiment with PHP code in the terminal in an interactive manner. If you make a mistake, it doesn't matter, Boris will report the error and stand to attention for further input.

mozey
  • 2,222
  • 2
  • 27
  • 34