PHP.mk документација

Интерактивна школка

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

features.commandline.interactive.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека features.commandline.interactive.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
Интерактивна школка

Референца за `features.commandline.interactive.php` со подобрена типографија и навигација.

features.commandline.interactive.php

Интерактивна школка

На CLI SAPI обезбедува интерактивна школка користејќи го -a опцијата ако PHP е компајлиран со --with-readline опцијата. Од PHP 7.1.0, интерактивната школка е достапна и на Windows, ако readline екстензија е овозможено.

Со користење на интерактивната школка, можете да пишувате PHP код и тој да се извршува директно.

Пример #1 Извршување код со користење на интерактивната школка

$ php -a
Interactive shell

php > echo 5+8;
13
php > function addTwo($n)
php > {
php { return $n + 2;
php { }
php > var_dump(addtwo(2));
int(4)
php >

Интерактивната школка исто така нуди комплетирање со таб за функции, константи, имиња на класи, променливи, статични повици на методи и класни константи.

Пример #2 Комплетирање со таб

Притискање на таб копчето двапати кога има повеќе можни комплетирања ќе резултира со листа на тие комплетирања:

php > strp[TAB][TAB]
strpbrk   strpos    strptime  
php > strp

Кога има само едно можно комплетирање, притискање на таб еднаш ќе го комплетира остатокот на истата линија:

php > strpt[TAB]ime(

Комплетирањето ќе работи и за имиња што се дефинирани за време на тековната сесија на интерактивната школка:

php > $fooThisIsAReallyLongVariableName = 42;
php > $foo[TAB]ThisIsAReallyLongVariableName

Интерактивната школка ја чува вашата историја до која може да се пристапи со копчињата горе и долу. Историјата се зачувува во ~/.php_history датотека. Од PHP 8.4.0, патеката до датотеката со историја може да се постави со користење на PHP_HISTFILE променливата на околината.

На CLI SAPI обезбедува php.ini settings cli.pager and cli.promptќе треба да се прилагоди, и cli.pager поставката дозволува надворешна програма (како less) да дејствува како прелистувач за излезот наместо да се прикажува директно на екранот. Поставката cli.prompt поставката го прави можно да се промени php > prompt.

Исто така е можно да се постави php.ini поставки во интерактивната школка користејќи кратка нотација.

Пример #3 Поставување php.ini поставки во интерактивниот шел

На cli.prompt поставка:

php > #cli.prompt=hello world :> 
hello world :>

Со користење на обратни апострофи, можно е да се изврши PHP код во промпт:

php > #cli.prompt=`echo date('H:i:s');` php > 
15:49:35 php > echo 'hi';
hi
15:49:43 php > sleep(2);
15:49:45 php >

Поставување на пеџер на less:

php > #cli.pager=less
php > phpinfo();
(output displayed in less)
php >

На cli.prompt поставката поддржува неколку секвенци за бегство:

cli.prompt секвенци за бегство
Секвенца = NULL
\e Се користи за додавање бои во промпт. Пример може да биде \e[032m\v \e[031m\b \e[34m\> \e[0m
\v PHP верзијата.
\b Укажува во кој блок е PHP. На пример /* за да се означи дека сте во повеќелиниски коментар. Надворешниот опсег е означен со php.
\> Укажува на карактерот на промпт. Стандардно е >, но се менува кога шелот е во незавршен блок или стринг. Можни карактери се: ' " { ( >

Забелешка:

Датотеките вклучени преку auto_prepend_file and auto_append_file се парсираат во овој режим, но со некои ограничувања - на пр. функциите мора да бидат дефинирани пред да бидат повикани.

Интерактивен режим

Ако екстензијата readline не е достапна, пред PHP 8.1.0, повикувањето на CLI SAPI со -a опцијата обезбеди интерактивен режим. Во овој режим, комплетен PHP скрипт треба да се даде преку STDIN, и по завршување со CTRL +D (POSIX) или CTRL +Z следено од +ENTER (Windows), овој скрипт се проценува. Ова е во основа исто како повикување на CLI SAPI без -a option.

Од PHP 8.1.0, повикувањето на CLI SAPI со -a опцијата не успева, ако екстензијата readline не е достапна.

Белешки од корисници Управување со PDO конекции

Рајан П
пред 14 години
Interactive Shell and Interactive Mode are not the same thing, despite the similar names and functionality.

If you type 'php -a' and get a response of 'Interactive Shell' followed by a 'php>' prompt, you have interactive shell available (PHP was compiled with readline support). If instead you get a response of 'Interactive mode enabled', you DO NOT have interactive shell available and this article does not apply to you.

You can also check 'php -m' and see if readline is listed in the output - if not, you don't have interactive shell.

Interactive mode is essentially like running php with stdin as the file input. You just type code, and when you're done (Ctrl-D), php executes whatever you typed as if it were a normal PHP (PHTML) file - hence you start in interactive mode with '<?php' in order to execute code.

Interactive shell evaluates every expression as you complete it (with ; or }), reports errors without terminating execution, and supports standard shell functionality via readline (history, tab completion, etc). It's an enhanced version of interactive mode that is ONLY available if you have the required libraries, and is an actual PHP shell that interprets everything you type as PHP code - using '<?php' will cause a parse error.

Finally, if you're running on Windows, you're probably screwed. From what I'm seeing in other comments here, you don't have readline, and without readline there is no interactive shell.
Readline
пред 14 години
In Windows, press Enter after your ending PHP tag and then hit Ctrl-Z to denote the end-of-file:

C:\>php -a
Interactive mode enabled

<?php
echo "Hello, world!";
?>
^Z
Hello, world!

You can use the up and down arrows in interactive mode to recall previous code you ran.
#linuxmint-es
пред 8 години
For use interactive mode enabled on GNU/Linux on distros Debian/Ubuntu/LinuxMint you must install "php*-cli" and "php*-readline" packages from official repository.
Example:
 >$sudo aptitude install php5-cli php5-readline

After that you can use interactive mode.
Example:
~ $ php -a
Interactive mode enabled

php >echo "hola mundo!\n";
hola mundo!
php >

I hope somebody help it!
Анонимен
пред 15 години
Just a few more notes to add...

1) Hitting return does literally mean "execute this command".  Semicolon to note end of line is still required.  Meaning, doing the following will produce a parse error:

php > print "test"
php > print "asdf";

Whereas doing the following is just fine:

php > print "test"
php > ."asdf";

2) Fatal errors may eject you from the shell:

name@local:~$ php -a
php > asdf();

Fatal Error: call to undefined function...
name@local:~$

3) User defined functions are not saved in history from shell session to shell session.

4) Should be obvious, but to quit the shell, just type "quit" at the php prompt.

5) In a sense, the shell interaction can be thought of as linearly following a regular php file, except it's live and dynamic.  If you define a function that you've already defined earlier in your current shell, you will receive a fatal "function already defined" error only upon entering that closing bracket.  And, although "including" a toolset of custom functions or a couple of script addon php files is rather handy, should you edit those files and wish to "reinclude" it again, you'll cause a fatal "function x already defined" error.
joeri at sebrechts dot net
пред 8 години
If you delete your "~/.php_history", you MUST re-create the file manually!

Because after I deleted my history file, "php -a" (interactive mode) never saved any history anymore.

It only started working after I ran "touch ~/.php_history" to create an empty file. From then on, PHP is saving history again!

I thought this was a bit unusual. Normally, applications recreate their history files themselves. But just be aware of the fact that PHP works this way instead, guys and girls! :-)
Сива
пред 6 години
When adding colours, don't forget that PHP uses the same 'readline' as Bash does, so it has the same need to wrap all colour codes in special marker characters.

If you simply add raw colour codes to the prompt, you will notice that long lines no longer get wrapped correctly -- Readline no longer knows how wide the prompt is.

To fix this, you need to start each colour code with an '0x01' byte (aka Ctrl-A aka SOH) and end it with the '0x02' byte (aka Ctrl-B aka STX). There are no escapes for these -- you have to literally put the control characters in your php-cli.ini.

For example:

<?php

// cli.prompt = <SOH>\e[1m<STX> PHP! \> <SOH>\e[m<STX>

echo "cli.prompt = \x01\\e[1m\x02 PHP! \x01\\e[m\x02\n";
?>
turabgarip на gmail точка com
пред 1 година
Note that destructors will not be triggered when exiting interactive shell by any method. (Like CTRL + D, CTRL + Z or CTRL + C).

Since the interactive shell is effectively a continuous runtime, the "end of script" condition is never met for a destructor to run. And exiting the interactive shell is not considered end of script but rather the end of interpreter process. And since the process is dead; it can't run the destructor.

Therefore the only way for a destructor to run is that you remove all the references to the corresponding object. Like:

<?php

class A {
    public function __destructor() {
        // This will never run after ending PHP interactive shell session.
    }
}

$a = new A();

// This is the only way for the destructor to be able to run.
$a = null; // Or;
unset($a);

?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.