Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialising PHP interactive

Tags:

php

I often find PHP's interactive mode -- php -a -- very useful but it would be far more useful if I could start it and have a few commands executed right away to initialize my environment. Things like run the autoloader, setup a few use shortcuts for namespaces, etc.

Here's an example:

include "../../autoloader.php";
use App/Foo/Bar as Bar;

I thought maybe I could just add these lines to a text file initialize.txt and then start the interactive mode with php -a < initialize.txt but that didn't work.

Anyone know how to do this?

like image 963
ken Avatar asked Aug 18 '13 00:08

ken


People also ask

How do I run PHP in interactive mode?

Interactive mode ¶ In this mode, a complete PHP script is supposed to be given via STDIN, and after termination with CRTL+d (POSIX) or CTRL+z followed by ENTER (Windows), this script is evaluated. This is basically the same as invoking the CLI SAPI without the -a option. As of PHP 8.1.

What is CLI PHP?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.

Does PHP have a REPL?

PHP in an HTML repl just shows the code. BUT, you can make a PHP repl and then add HTML files and, if you want, more PHP files. IMPORTANT NOTE: Use PHP Web Server for HTML, not PHP CLI.


1 Answers

As Tomas Creemers mentioned, you have to use auto_prepend_file PHP flag to auto-require a file. For example:

<?php
# foo.php
function bar() { print "Bar.\n"; }

You can load PHP interpreter like this:

[hron@merlin tmp ] $ php -d auto_prepend_file=$PWD/foo.php -a
Interactive shell

php > bar();
Bar.
php >

Or you can include file manually:

[hron@merlin tmp ] $ php -a
Interactive shell

php > include 'foo.php';
php > bar();
Bar.
php > 
like image 144
Gabor Garami Avatar answered Sep 29 '22 12:09

Gabor Garami