EasyТеория4 min

Синтаксис PHP

Теги, точки с запятой, комментарии и лучшие практики

Открывающие и закрывающие теги

PHP-код размещается внутри специальных тегов. Существует несколько вариантов:

<?php
// Standard opening tag — ЕДИНСТВЕННЫЙ рекомендуемый способ
echo 'Hello, World!';
?>

Виды тегов

Тег Пример Статус
Стандартный <?php ... ?> Рекомендуемый, всегда доступен
Короткий echo <?= $var ?> Всегда доступен с PHP 5.4+
Короткий <? ... ?> Зависит от short_open_tag, НЕ рекомендуется
ASP-стиль <% ... %> Удалён в PHP 7.0
Script-тег <script language="php"> Удалён в PHP 7.0
<?php
declare(strict_types=1);

// Short echo tag — всегда доступен начиная с PHP 5.4
$name = 'PHP';
?>

<!-- In templates -->
<h1><?= $name ?></h1>
<!-- Equivalent to: <?php echo $name; ?> -->

Ловушка экзамена: Короткий тег <? зависит от директивы short_open_tag в php.ini. Короткий echo-тег <?= доступен ВСЕГДА начиная с PHP 5.4, независимо от настройки short_open_tag. Это частый вопрос на экзамене!

Закрывающий тег

<?php
declare(strict_types=1);

// If the file contains ONLY PHP code,
// the closing tag SHOULD be omitted
echo 'No closing tag needed';

// PSR-12: Files MUST NOT use the closing tag

Запомни: Если файл содержит только PHP-код, закрывающий тег ?> ДОЛЖЕН быть опущен (стандарт PSR-12). Это предотвращает случайные пробелы после закрывающего тега, которые могут вызвать ошибки "headers already sent".

Точка с запятой

Каждая инструкция (statement) в PHP обязательно завершается точкой с запятой:

<?php
declare(strict_types=1);

echo 'Hello';   // Correct
echo 'World';   // Correct

// The last statement before a closing tag
// does NOT require a semicolon (but it's bad practice)
?>
<?php echo 'test' ?>

Ловушка экзамена: Последнее выражение перед закрывающим тегом ?> может не иметь точки с запятой. Но это считается плохой практикой. На экзамене могут спросить, скомпилируется ли такой код — ответ: ДА.

<?php
declare(strict_types=1);

// This is valid but NOT recommended
echo 'Hello'
?>

Комментарии

PHP поддерживает три стиля комментариев:

<?php
declare(strict_types=1);

// Single-line comment (C++ style)

# Single-line comment (Shell style)

/*
 * Multi-line comment
 * (C style)
 */

/**
 * PHPDoc comment — used for documentation
 *
 * @param string $name User name
 * @return string Greeting message
 */
function greet(string $name): string
{
    return "Hello, {$name}!";
}

Вложенные комментарии

<?php
declare(strict_types=1);

/*
echo 'This is commented out';
// Nested single-line comment — this is fine
echo 'Also commented out';
*/

/*
echo 'Start of outer comment';
/* echo 'Nested block comment'; */  // ERROR! This ends the outer comment
echo 'This will execute and likely cause errors';
*/

Ловушка экзамена: Блочные комментарии /* */ НЕ могут быть вложенными! Первый встреченный */ закроет комментарий. Однако однострочные комментарии // и # внутри блочного комментария работают нормально.

Идентификаторы и именование

Правила именования переменных

<?php
declare(strict_types=1);

// Variable names are case-SENSITIVE
$name = 'John';
$Name = 'Jane';      // Different variable!
$NAME = 'JACK';      // Yet another variable!

// Valid variable names
$_var   = 1;          // Starts with underscore
$var2   = 2;          // Contains digits
$café   = 'coffee';   // UTF-8 characters allowed (PHP 7.0+)

// Invalid variable names
// $2var  = 1;         // Cannot start with a digit
// $my-var = 1;        // Hyphens not allowed
// $my var = 1;        // Spaces not allowed

Чувствительность к регистру

<?php
declare(strict_types=1);

// Functions are case-INSENSITIVE
function sayHello(): void {
    echo 'Hello!';
}
SAYHELLO();  // Works! (but not recommended)
sayHello();  // Preferred

// Class names are case-INSENSITIVE
class MyClass {}
$obj = new MYCLASS();  // Works!
$obj = new myclass();  // Works!

// Constants defined with 'const' are case-SENSITIVE
const MY_CONST = 42;
// echo my_const;  // Error: undefined constant

// Variables are ALWAYS case-SENSITIVE
$foo = 'bar';
// echo $FOO;  // Error: undefined variable

Запомни: Таблица чувствительности к регистру:

Элемент Чувствителен к регистру?
Переменные ДА
Константы (const) ДА
Имена функций НЕТ
Имена классов НЕТ
Ключевые слова НЕТ
true/false/null НЕТ

Директива declare(strict_types=1)

<?php
declare(strict_types=1);

// With strict_types=1, PHP will NOT auto-convert types
function add(int $a, int $b): int
{
    return $a + $b;
}

echo add(2, 3);      // 5
// echo add(2, '3'); // TypeError! String '3' not accepted

// Without strict_types (default behavior):
// add(2, '3') would return 5 (auto-conversion)

Важные правила declare

<?php
// declare MUST be the first statement in the file
// (except comments and whitespace)
declare(strict_types=1);

// Only these directives exist:
// declare(strict_types=1);   — strict type checking
// declare(encoding='UTF-8'); — file encoding
// declare(ticks=1);          — tick interval

Ловушка экзамена: declare(strict_types=1) влияет только на файл, в котором объявлен. Если функция объявлена в файле A с strict_types=1, но вызывается из файла B без этой директивы — проверка типов при вызове зависит от настройки в файле B (вызывающем), а НЕ в файле A.

<?php
// file: math.php
declare(strict_types=1);

function multiply(int $a, int $b): int
{
    return $a * $b;
}
<?php
// file: app.php (NO strict_types)
require 'math.php';

// This works because strict_types is checked
// in the CALLING file (app.php), not in math.php
echo multiply(2, '3');  // 6 (string '3' auto-converted)

Разделение инструкций

<?php
declare(strict_types=1);

// Each statement needs a semicolon
$a = 1;
$b = 2;
$c = $a + $b;

// Multiple statements on one line (valid but bad style)
$x = 1; $y = 2; $z = 3;

// Control structures use braces, not semicolons
if ($a > 0) {
    echo 'Positive';
}  // No semicolon after brace

// But single-line alternative syntax
if ($a > 0)
    echo 'Positive';  // Semicolon here

Встраивание PHP в HTML

<!DOCTYPE html>
<html>
<body>
    <?php
    declare(strict_types=1);

    $items = ['Apple', 'Banana', 'Cherry'];
    ?>

    <ul>
    <?php foreach ($items as $item): ?>
        <li><?= htmlspecialchars($item, ENT_QUOTES, 'UTF-8') ?></li>
    <?php endforeach; ?>
    </ul>
</body>
</html>

Запомни: Альтернативный синтаксис (if/endif, foreach/endforeach, while/endwhile, for/endfor, switch/endswitch) используется ТОЛЬКО при смешивании PHP и HTML. В чистом PHP-коде используйте фигурные скобки.

Лучшие практики (PSR-12)

<?php
// PSR-12 standard requirements:
// 1. Files MUST use only <?php and <?= tags
// 2. Files MUST use only UTF-8 without BOM
// 3. Files SHOULD either declare symbols OR cause side-effects, not both
// 4. Closing tag MUST be omitted in PHP-only files
// 5. There MUST NOT be trailing whitespace at end of lines
// 6. Lines SHOULD be 120 characters or less
// 7. There MUST be one blank line after the namespace declaration
// 8. Opening braces for classes/methods MUST go on the next line
// 9. Opening braces for control structures MUST go on the same line

declare(strict_types=1);

namespace App\Service;

use App\Entity\User;
use App\Repository\UserRepository;

final class UserService
{
    public function __construct(
        private readonly UserRepository $repository,
    ) {
    }

    public function findByEmail(string $email): ?User
    {
        if (empty($email)) {
            return null;
        }

        return $this->repository->findOneBy(['email' => $email]);
    }
}

Вопросы с экзамена ZCE

Проверь себя

5 из 50

Какой правильный способ прибавить 1 к переменной `$count`?

Выберите все правильные варианты

Рассмотрите следующий PHP-скрипт: Что нужно написать, чтобы вывести значение 'Web development'? ```php $a = [ '1' => "php", "Hypertext", "Preprocessor", "widely used" => [ 'general' => 'purpose', 'scripting' => 'language', 'that' => 'was', 'originally' => [ 5 => 'designed', 9 => 'for', 'Web development', 4 => 'purpose' ] ] ]; //write code here ```

Какие из следующих тегов допустимы для начала блока PHP-кода (PHP 5.3)? (Выберите 3)

Выберите все правильные варианты

Как закомментировать код в PHP-скрипте?

Вы выполняете следующий PHP-скрипт: ```php $a = 12; $b = 11; $a > $b ? print($a) : print($b); ```