Апострофи
Найпростіший спосіб означити рядок (string) — взяти його в
апострофи (наприклад 'це рядкове значення'
).
Щоб вписати в рядок апостроф, цей знак необхідно екранувати
оберненою косою рискою (\
). Щоб всередині рядкового
значення вписати обернену косу риску, треба продублювати її
(\\
). Всі наступні символи оберненої косої риски будуть
сприйматись буквально: це означає, що всі інші екрановані послідовності,
наприклад \r
або \n
будуть виводитись
буквально, а не як такі, що мають спеціальне значення.
Зауваження:
На відміну від
лапок
та синтаксису
heredoc,
змінні та екрановані
послідовності спеціальних символів не будуть
розкриті в рядках, взятих в апострофи.
Heredoc
Третій спосіб запису значення типу string — синтаксис heredoc:
<<<
. Після цього оператора слідують
мітка та символ нового рядка. Далі — власне, текст (string), а
потім та сама мітка з нового рядка. Вона позначає кінець тексту.
В кінці перед міткою можуть бути пропуски або символи табуляції. Тоді такі ж
відступи будуть видалені з початку усіх рядків тексту. До PHP 7.3.0, мітка в
кінці повинна бути одразу після символа нового рядка.
Також мітка має відповідати правилам називання міткок в PHP: містити тільки
букви, цифри, підкреслення та починатися з букви або підкреслення.
Приклад #1 Простий приклад Heredoc, починаючи з PHP 7.3.0
<?php
// без відступів
echo <<<МІТКА
а
б
в
\n
МІТКА;
// відступ з 4-х пропусків
echo <<<МІТКА
а
б
в
МІТКА;
В PHP 7.3 поданий вище приклад
виведе:
Якщо кінцева мітка відступає далі ніж будь-який рядок тексту, то викинеться
ParseError:
Приклад #2 Кінцева мітка не має відступати далі ніж будь-який рядок тексту
<?php
echo <<<МІТКА
а
б
в
МІТКА;
В PHP 7.3 поданий вище приклад
виведе:
PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4
Для відступу кінцевої мітки можна використовувати табуляцію, однак табуляція
та пропуски не повинні змішуватися у відступах тексту
чи кінцевої мітки. Інакше, буде викинуто ParseError.
Це обмеження було введено у зв'язку з тим, що змішування табуляції та
пропусків погіршує розбірливість коду.
Приклад #3 Різні відступи
<?php
// Увесь наступний код не працює.
// різні відступи в тексті (пропуски) та для кінцевої мітки (табуляція)
{
echo <<<МІТКА
а
МІТКА;
}
// змішування пропусків та табуляції в тексті
{
echo <<<МІТКА
а
МІТКА;
}
// змішування пропусків та табуляції для кінцевої мітки
{
echo <<<МІТКА
а
МІТКА;
}
В PHP 7.3 поданий вище приклад
виведе:
PHP Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8
Крапка з комою чи символ нового рядка після кінцевої мітки не є
обов'язковими. До прикладу, наступний код дозволений, починаючи з PHP 7.3.0:
Приклад #4 Продовження виразу після кінцевої мітки
<?php
$значення = [<<<МІТКА
а
б
в
МІТКА, 'г ґ д'];
var_dump($значення);
В PHP 7.3 поданий вище приклад
виведе:
array(2) {
[0]=>
string(14) "а
б
в"
[1]=>
string(8) "г ґ д"
}
Увага
Якщо назву мітки знайдено одразу після символу початку рядка, то навіть
якщо це була частина тексту, вона розглядатиметься як кінцева мітка, що
спричинить помилку ParseError.
Приклад #5 Кінцева мітка в тексті може викликати ParseError
<?php
$значення = [<<<МІТКА
а
б
МІТКА помічає кінець тексту
МІТКА, 'в г ґ'];
В PHP 7.3 поданий вище приклад
виведе:
PHP Parse error: syntax error, unexpected identifier "помічає", expecting "]" in example.php on line 5
Щоб уникнути цієї проблеми, безпечніше дотримуватися простого правила:
не обирати мітку, яка може з'явитися в тексті.
Увага
До PHP 7.3.0, необхідно слідкувати за тим, щоб рядок з кінцевою міткою не
містив нічого, крім самої мітки та крапки з комою (;
) за
нею. Це означає, що мітка не може відступати від
початку рядка, а також не може бути жодних пропусків чи табуляції перед чи
після крапки з комою. Також важливо, щоб символом перед кінцевою міткою
був символ нового рядка, визначений локальною операційною системою. Це
\n
в системах UNIX, включно з macOS. Також цей символ
має бути одразу після крапки з комою.
Якщо це правило порушено і кінцева мітка неправильна — вона не
вважатиметься такою, а PHP продовжить шукати кінцеву мітку. Якщо до кінця
поточного файлу мітку не буде знайдено, то на останньому рядку виникне
синтаксична помилка.
Приклад #6 Недійсна мітка, до версії PHP 7.3.0
<?php
class foo {
public $bar = <<<МІТКА
bar
МІТКА;
}
// Мітка повинна не мати відступів
?>
Приклад #7 Дійсна мітка, навіть до версії PHP 7.3.0
<?php
class foo {
public $bar = <<<МІТКА
bar
МІТКА;
}
?>
Дані рядкового типу в синтаксисі Heredoc, які містять змінні, не можна
використовувати для ініціалізації властивостей класу.
Текст Heredoc має ті ж особливості, що і рядок (string) в
лапках, просто без лапок. Це означає, що лапки в Heredoc не потрібно
екранувати, а перелічені вище екрановані послідовності досі можна
використовувати. Змінні так само розкриваються, а складні змінні записуються
тим же способом, що і в рядках (string).
Приклад #8 Вставлення інших рядків в Heredoc
<?php
$str = <<<EOD
Приклад тексту
з синтаксисом heredoc,
що складається з кількох рядків.
EOD;
/* Складніший приклад, зі змінними. */
class foo
{
var $foo;
var $bar;
function __construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'Петро';
echo <<<EOT
Мене звати $name. Я друкую $foo->foo.
Зараз я друкую {$foo->bar[1]}.
Має надрукуватись велика буква 'A': \x41
EOT;
?>
Поданий вище приклад
виведе:
Мене звати Петро. Я друкую Foo.
Зараз я друкую Bar2.
Має надрукуватись велику буква 'A': A
Також можливо використовувати Heredoc-синтаксис для передавання параметрів
до функції:
Приклад #9 Heredoc в значеннях параметрів
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
Можна задавати значення статичним змінним та властивостям/константам класу,
використовуючи синтаксис Heredoc:
Приклад #10 Heredoc як статичне значення
<?php
// Поле класу
function foo()
{
static $bar = <<<LABEL
Тут нічого цікавого...
LABEL;
}
// Властивість, константа класу
class foo
{
const BAR = <<<FOOBAR
Приклад константи
FOOBAR;
public $baz = <<<FOOBAR
Приклад властивості
FOOBAR;
}
?>
Початкову мітку Heredoc можна брати в лапки:
Приклад #11 Використання лапок в Heredoc
<?php
echo <<<"FOOBAR"
Привіт, світ!
FOOBAR;
?>
Nowdoc
Синтаксис nowdoc стосується рядків в апострофах, як heredoc — рядків в
лапках, тобто працює схожим способом до heredoc, але без парсингу
тексту всередині. Така конструкція прекрасно підходить
для вставлення PHP-коду або великих частин тексту без необхідності їхнього
екранування. Цей синтаксис має деякі спільні риси з конструкцією SGML
<![CDATA[ ]]>
, оскільки він оголошує блок тексту,
який не підлягає аналізу.
Nowdoc починається з тої ж послідовності <<<
, що
й heredocs, але назва мітки, що йде далі, береться в апострофи, напр.
<<<'EOT'
. Усі правила щодо міток heredoc
застосовуються також до міток nowdoc, особливо ті, що стосуються кінцевої
мітки.
Приклад #12 Приклад тексту nowdoc
<?php
echo <<<'МІТКА'
Приклад тексту з кількома рядками
з використанням синтаксису nowdoc.
Зворотні косі риски завжди спиймаються буквально, напр. \\ і \'.
МІТКА;
Поданий вище приклад
виведе:
Приклад тексту з кількома рядками
з використанням синтаксису nowdoc.
Зворотні косі риски завжди спиймаються буквально, напр. \\ і \'.
Приклад #13 Текст nowdoc зі змінними всередині
<?php
class foo
{
public $foo;
public $bar;
function __construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'Петро';
echo <<<'EOT'
Мене звати $name. Я друкую $foo->foo.
Зараз я друкую {$foo->bar[1]}.
Має НЕ надрукуватись велика буква 'A': \x41
EOT;
?>
Поданий вище приклад
виведе:
Мене звати $name. Я друкую $foo->foo.
Зараз я друкую {$foo->bar[1]}.
Має НЕ надрукуватись велику буква 'A': \x41
Приклад #14 Зі статичними даними
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Обробка змінних
Якщо рядок (string) записано в лапках або в heredoc, то
змінні в ньому — обробляються.
Є два способи запису:
простий та
складний.
Простий синтаксис є найпоширенішим і найзручнішим. Він надає можливість
вбудувати змінну, значення масиву (array), або властивість
об'єкта (object) в рядок (string) з невеликими
зусиллями.
Складний синтаксис можна розпізнати за фігурними дужками, в які обрамлено
вираз.
Simple syntax
If a dollar sign ($
) is encountered, the parser will
greedily take as many tokens as possible to form a valid variable name.
Enclose the variable name in curly braces to explicitly specify the end of
the name.
Similarly, an array index or an object property
can be parsed. With array indices, the closing square bracket
(]
) marks the end of the index. The same rules apply to
object properties as to simple variables.
Приклад #15 Simple syntax example
<?php
$juices = array("apple", "orange", "koolaid1" => "purple");
echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public $smith = "Smith";
}
$people = new people();
echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>
Поданий вище приклад
виведе:
He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .
As of PHP 7.1.0 also negative numeric indices are
supported.
Приклад #16 Negative numeric indices
<?php
$string = 'string';
echo "The character at index -2 is $string[-2].", PHP_EOL;
$string[-3] = 'o';
echo "Changing the character at index -3 to o gives $string.", PHP_EOL;
?>
Поданий вище приклад
виведе:
The character at index -2 is n.
Changing the character at index -3 to o gives strong.
For anything more complex, you should use the complex syntax.
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it
allows for the use of complex expressions.
Any scalar variable, array element or object property with a
string representation can be included via this syntax.
The expression is written the same way as it would appear outside the
string, and then wrapped in {
and
}
. Since {
can not be escaped, this
syntax will only be recognised when the $
immediately
follows the {
. Use {\$
to get a
literal {$
. Some examples to make it clear:
It is also possible to access class properties using variables
within strings using this syntax.
Зауваження:
The value accessed from functions, method calls, static class variables,
and class constants inside
{$}
will be interpreted as the name
of a variable in the scope in which the string is defined. Using
single curly braces ({}
) will not work for
accessing the return values of functions or methods or the
values of class constants or static class variables.
String access and modification by character
Characters within strings may be accessed and modified by
specifying the zero-based offset of the desired character after the
string using square array brackets, as in
$str[42]. Think of a string as an
array of characters for this purpose. The functions
substr() and substr_replace()
can be used when you want to extract or replace more than 1 character.
Зауваження:
As of PHP 7.1.0, negative string offsets are also supported. These specify
the offset from the end of the string.
Formerly, negative offsets emitted E_NOTICE
for reading
(yielding an empty string) and E_WARNING
for writing
(leaving the string untouched).
Зауваження:
Prior to PHP 8.0.0, strings could also be accessed using braces, as in
$str{42}, for the same purpose.
This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
Увага
Writing to an out of range offset pads the string with spaces.
Non-integer types are converted to integer.
Illegal offset type emits E_WARNING
.
Only the first character of an assigned string is used.
As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly,
it assigned a NULL byte.
Увага
Internally, PHP strings are byte arrays. As a result, accessing or
modifying a string using array brackets is not multi-byte safe, and
should only be done with strings that are in a single-byte encoding such
as ISO-8859-1.
Зауваження:
As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal
error. Formerly, the empty string was silently converted to an array.
Приклад #17 Some string examples
<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];
// Get the third character of a string
$third = $str[2];
// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];
// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';
?>
String offsets have to either be integers or integer-like strings,
otherwise a warning will be thrown.
Приклад #18 Example of Illegal String Offsets
<?php
$str = 'abc';
var_dump($str['1']);
var_dump(isset($str['1']));
var_dump($str['1.0']);
var_dump(isset($str['1.0']));
var_dump($str['x']);
var_dump(isset($str['x']));
var_dump($str['1x']);
var_dump(isset($str['1x']));
?>
Поданий вище приклад
виведе:
string(1) "b"
bool(true)
Warning: Illegal string offset '1.0' in /tmp/t.php on line 7
string(1) "b"
bool(false)
Warning: Illegal string offset 'x' in /tmp/t.php on line 9
string(1) "a"
bool(false)
string(1) "b"
bool(false)
Зауваження:
Accessing variables of other types (not including arrays or objects
implementing the appropriate interfaces) using []
or
{}
silently returns null
.
Зауваження:
Characters within string literals can be accessed
using []
or {}
.
Зауваження:
Accessing characters within string literals using the
{}
syntax has been deprecated in PHP 7.4.
This has been removed in PHP 8.0.