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?
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.
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.
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.
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 >
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With