Меню

Syntax error unexpected php ошибка

Антон Шевчук // Web-разработчик

Не совершает ошибок только тот, кто ничего не делает, и мы тому пример – трудимся не покладая рук над созданием рабочих мест для тестировщиков 🙂

О да, в этой статье я поведу свой рассказа об ошибках в PHP, и том как их обуздать.

Ошибки

Разновидности в семействе ошибок

Перед тем как приручать ошибки, я бы рекомендовал изучить каждый вид и отдельно обратить внимание на самых ярких представителей.

Чтобы ни одна ошибка не ушла незамеченной потребуется включить отслеживание всех ошибок с помощью функции error_reporting(), а с помощью директивы display_errors включить их отображение:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

Фатальные ошибки

Самый грозный вид ошибок – фатальные, они могут возникнуть как при компиляции, так и при работе парсера или PHP-скрипта, выполнение скрипта при этом прерывается.

E_PARSE
Это ошибка появляется, когда вы допускаете грубую ошибку синтаксиса и интерпретатор PHP не понимает, что вы от него хотите, например если не закрыли фигурную или круглую скобочку:

<?php
/**
 Parse error: syntax error, unexpected end of file
 */
{

Или написали на непонятном языке:

<?php
/**
 Parse error: syntax error, unexpected '...' (T_STRING)
 */
Тут будет ошибка парсера

Лишние скобочки тоже встречаются, и не важно круглые либо фигурные:

<?php
/**
 Parse error: syntax error, unexpected '}'
 */
}

Отмечу один важный момент – код файла, в котором вы допустили parse error не будет выполнен, следовательно, если вы попытаетесь включить отображение ошибок в том же файле, где возникла ошибка парсера то это не сработает:

<?php
// этот код не сработает
error_reporting(E_ALL);
ini_set('display_errors', 1);

// т.к. вот тут
ошибка парсера

E_ERROR
Это ошибка появляется, когда PHP понял что вы хотите, но сделать сие не получилось ввиду ряда причин, так же прерывает выполнение скрипта, при этом код до появления ошибки сработает:

Не был найден подключаемый файл:

/**
 Fatal error: require_once(): Failed opening required 'not-exists.php' (include_path='.:/usr/share/php:/usr/share/pear')
 */
require_once 'not-exists.php';

Было брошено исключение (что это за зверь, расскажу немного погодя), но не было обработано:

/**
 Fatal error: Uncaught exception 'Exception'
 */
throw new Exception();

При попытке вызвать несуществующий метод класса:

/**
 Fatal error: Call to undefined method stdClass::notExists()
 */
$stdClass = new stdClass();
$stdClass->notExists();

Отсутствия свободной памяти (больше, чем прописано в директиве memory_limit) или ещё чего-нить подобного:

/**
 Fatal Error: Allowed Memory Size
 */
$arr = array();

while (true) {
    $arr[] = str_pad(' ', 1024);
}

Очень часто происходит при чтении либо загрузки больших файлов, так что будьте внимательны с вопросом потребляемой памяти

Рекурсивный вызов функции. В данном примере он закончился на 256-ой итерации, ибо так прописано в настройках xdebug:

/**
 Fatal error: Maximum function nesting level of '256' reached, aborting!
 */
function deep() {
    deep();
}
deep();

Не фатальные

Данный вид не прерывает выполнение скрипта, но именно их обычно находит тестировщик, и именно они доставляют больше всего хлопот у начинающих разработчиков.

E_WARNING
Частенько встречается, когда подключаешь файл с использованием include, а его не оказывается на сервере или ошиблись указывая путь к файлу:

/**
 Warning: include_once(): Failed opening 'not-exists.php' for inclusion
 */
include_once 'not-exists.php';

Бывает, если используешь неправильный тип аргументов при вызове функций:

/**
 Warning: join(): Invalid arguments passed
 */
join('string', 'string');

Их очень много, и перечислять все не имеет смысла…

E_NOTICE
Это самые распространенные ошибки, мало того, есть любители отключать вывод ошибок и клепают их целыми днями. Возникают при целом ряде тривиальных ошибок.

Когда обращаются к неопределенной переменной:

/**
 Notice: Undefined variable: a
 */
echo $a;

Когда обращаются к несуществующему элементу массива:

<?php
/**
 Notice: Undefined index: a
 */
$b = array();
$b['a'];

Когда обращаются к несуществующей константе:

/**
 Notice: Use of undefined constant UNKNOWN_CONSTANT - assumed 'UNKNOWN_CONSTANT'
 */
echo UNKNOWN_CONSTANT;

Когда не конвертируют типы данных:

/**
 Notice: Array to string conversion
 */
echo array();

Для избежания подобных ошибок – будьте внимательней, и если вам IDE подсказывает о чём-то – не игнорируйте её:

PHP E_NOTICE in PHPStorm

E_STRICT
Это ошибки, которые научат вас писать код правильно, чтобы не было стыдно, тем более IDE вам эти ошибки сразу показывают. Вот например, если вызвали не статический метод как статику, то код будет работать, но это как-то неправильно, и возможно появление серьёзных ошибок, если в дальнейшем метод класса будет изменён, и появится обращение к $this:

/**
 Strict standards: Non-static method Strict::test() should not be called statically
 */
class Strict { 
    public function test() { 
        echo 'Test'; 
    } 
}

Strict::test();

E_DEPRECATED
Так PHP будет ругаться, если вы используете устаревшие функции (т.е. те, что помечены как deprecated, и в следующем мажорном релизе их не будет):

/**
 Deprecated: Function split() is deprecated
 */

// популярная функция, всё никак не удалят из PHP
// deprecated since 5.3
split(',', 'a,b');

В моём редакторе подобные функции будут зачёркнуты:

PHP E_DEPRECATED in PHPStorm

Обрабатываемые

Этот вид, которые разводит сам разработчик кода, я их уже давно не встречал, не рекомендую их вам заводить:

  • E_USER_ERROR – критическая ошибка
  • E_USER_WARNING – не критическая ошибка
  • E_USER_NOTICE – сообщения которые не являются ошибками

Отдельно стоит отметить E_USER_DEPRECATED – этот вид всё ещё используется очень часто для того, чтобы напомнить программисту, что метод или функция устарели и пора переписать код без использования оной. Для создания этой и подобных ошибок используется функция trigger_error():

/**
 * @deprecated Deprecated since version 1.2, to be removed in 2.0
 */
function generateToken() {
    trigger_error('Function `generateToken` is deprecated, use class `Token` instead', E_USER_DEPRECATED);
    // ...
    // code ...
    // ...
}

Теперь, когда вы познакомились с большинством видов и типов ошибок, пора озвучить небольшое пояснение по работе директивы display_errors:

  • если display_errors = on, то в случае ошибки браузер получит html c текстом ошибки и кодом 200
  • если же display_errors = off, то для фатальных ошибок код ответа будет 500 и результат не будет возвращён пользователю, для остальных ошибок – код будет работать неправильно, но никому об этом не расскажет

Приручение

Для работы с ошибками в PHP существует 3 функции:

  • set_error_handler() — устанавливает обработчик для ошибок, которые не обрывают работу скрипта (т.е. для не фатальных ошибок)
  • error_get_last() — получает информацию о последней ошибке
  • register_shutdown_function() — регистрирует обработчик который будет запущен при завершении работы скрипта. Данная функция не относится непосредственно к обработчикам ошибок, но зачастую используется именно для этого

Теперь немного подробностей об обработке ошибок с использованием set_error_handler(), в качестве аргументов данная функция принимает имя функции, на которую будет возложена миссия по обработке ошибок и типы ошибок которые будут отслеживаться. Обработчиком ошибок может так же быть методом класса, или анонимной функцией, главное, чтобы он принимал следующий список аргументов:

  • $errno – первый аргумент содержит тип ошибки в виде целого числа
  • $errstr – второй аргумент содержит сообщение об ошибке
  • $errfile – необязательный третий аргумент содержит имя файла, в котором произошла ошибка
  • $errline – необязательный четвертый аргумент содержит номер строки, в которой произошла ошибка
  • $errcontext – необязательный пятый аргумент содержит массив всех переменных, существующих в области видимости, где произошла ошибка

В случае если обработчик вернул true, то ошибка будет считаться обработанной и выполнение скрипта продолжится, иначе — будет вызван стандартный обработчик, который логирует ошибку и в зависимости от её типа продолжит выполнение скрипта или завершит его. Вот пример обработчика:

<?php
    // включаем отображение всех ошибок, кроме E_NOTICE
    error_reporting(E_ALL & ~E_NOTICE);
    ini_set('display_errors', 1);
    
    // наш обработчик ошибок
    function myHandler($level, $message, $file, $line, $context) {
        // в зависимости от типа ошибки формируем заголовок сообщения
        switch ($level) {
            case E_WARNING:
                $type = 'Warning';
                break;
            case E_NOTICE:
                $type = 'Notice';
                break;
            default;
                // это не E_WARNING и не E_NOTICE
                // значит мы прекращаем обработку ошибки
                // далее обработка ложится на сам PHP
                return false;
        }
        // выводим текст ошибки
        echo "<h2>$type: $message</h2>";
        echo "<p><strong>File</strong>: $file:$line</p>";
        echo "<p><strong>Context</strong>: $". join(', $', array_keys($context))."</p>";
        // сообщаем, что мы обработали ошибку, и дальнейшая обработка не требуется
        return true;
    }
    
    // регистрируем наш обработчик, он будет срабатывать на для всех типов ошибок
    set_error_handler('myHandler', E_ALL);

У вас не получится назначить более одной функции для обработки ошибок, хотя очень бы хотелось регистрировать для каждого типа ошибок свой обработчик, но нет – пишите один обработчик, и всю логику отображения для каждого типа описывайте уже непосредственно в нём

С обработчиком, который написан выше есть одна существенная проблема – он не ловит фатальные ошибки, и вместо сайта пользователи увидят лишь пустую страницу, либо, что ещё хуже, сообщение об ошибке. Дабы не допустить подобного сценария следует воспользоваться функцией register_shutdown_function() и с её помощью зарегистрировать функцию, которая всегда будет выполняться по окончанию работы скрипта:

function shutdown() {
    echo 'Этот текст будет всегда отображаться';
}
register_shutdown_function('shutdown');

Данная функция будет срабатывать всегда!

Но вернёмся к ошибкам, для отслеживания появления в коде ошибки воспользуемся функцией error_get_last(), с её помощью можно получить информацию о последней выявленной ошибке, а поскольку фатальные ошибки прерывают выполнение кода, то они всегда будут выполнять роль “последних”:

function shutdown() {
    $error = error_get_last();
    if (
        // если в коде была допущена ошибка
        is_array($error) &&
        // и это одна из фатальных ошибок
        in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])
    ) {
        // очищаем буфер вывода (о нём мы ещё поговорим в последующих статьях)
        while (ob_get_level()) {
            ob_end_clean();
        }
        // выводим описание проблемы
        echo 'Сервер находится на техническом обслуживании, зайдите позже';
    }
}
register_shutdown_function('shutdown');

Задание
Дополнить обработчик фатальных ошибок выводом исходного кода файла где была допущена ошибка, а так же добавьте подсветку синтаксиса выводимого кода.

О прожорливости

Проведём простой тест, и выясним – сколько драгоценных ресурсов кушает самая тривиальная ошибка:

/**
 * Этот код не вызывает ошибок
 */

// сохраняем параметры памяти и времени выполнения скрипта
$memory = memory_get_usage();
$time= microtime(true);

$a = '';
$arr = [];
for ($i = 0; $i < 10000; $i++) {
    $arr[$a] = $i;
}

printf('%f seconds <br/>', microtime(true) - $time);
echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';

В результате запуска данного скрипта у меня получился вот такой результат:

0.002867 seconds 
984 bytes

Теперь добавим ошибку в цикле:

/**
 * Этот код содержит ошибку
 */

// сохраняем параметры памяти и времени выполнения скрипта
$memory = memory_get_usage();
$time= microtime(true);

$a = '';
$arr = [];
for ($i = 0; $i < 10000; $i++) {
    $arr[$b] = $i; // тут ошиблись с именем переменной
}

printf('%f seconds <br/>', microtime(true) - $time);
echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';

Результат ожидаемо хуже, и на порядок (даже на два порядка!):

0.263645 seconds 
992 bytes

Вывод однозначен – ошибки в коде приводят к лишней прожорливости скриптов – так что во время разработки и тестирования приложения включайте отображение всех ошибок!

Тестирование проводил на PHP версии 5.6, в седьмой версии результат лучше – 0.0004 секунды против 0.0050 – разница только на один порядок, но в любом случае результат стоит прикладываемых усилий по исправлению ошибок

Где собака зарыта

В PHP есть спец символ «@» – оператор подавления ошибок, его используют дабы не писать обработку ошибок, а положится на корректное поведение PHP в случае чего:

<?php
    echo @UNKNOWN_CONSTANT;

При этом обработчик ошибок указанный в set_error_handler() всё равно будет вызван, а факт того, что к ошибке было применено подавление можно отследить вызвав функцию error_reporting() внутри обработчика, в этом случае она вернёт 0.

Если вы в такой способ подавляете ошибки, то это уменьшает нагрузку на процессор в сравнении с тем, если вы их просто скрываете (см. сравнительный тест выше), но в любом случае, подавление ошибок это зло

Исключения

В эру PHP4 не было исключений (exceptions), всё было намного сложнее, и разработчики боролись с ошибками как могли, это было сражение не на жизнь, а на смерть… Окунуться в эту увлекательную историю противостояния можете в статье Исключительный код. Часть 1. Стоит ли её читать сейчас? Думаю да, ведь это поможет вам понять эволюцию языка, и раскроет всю прелесть исключений

Исключения — исключительные событие в PHP, в отличии от ошибок не просто констатируют наличие проблемы, а требуют от программиста дополнительных действий по обработке каждого конкретного случая.

К примеру, скрипт должен сохранить какие-то данные в кеш файл, если что-то пошло не так (нет доступа на запись, нет места на диске), генерируется исключение соответствующего типа, а в обработчике исключений принимается решение – сохранить в другое место или сообщить пользователю о проблеме.

Исключение – это объект который наследуется от класса Exception, содержит текст ошибки, статус, а также может содержать ссылку на другое исключение которое стало первопричиной данного. Модель исключений в PHP схожа с используемыми в других языках программирования. Исключение можно инициировать (как говорят, “бросить”) при помощи оператора throw, и можно перехватить (“поймать”) оператором catch. Код генерирующий исключение, должен быть окружен блоком try, для того чтобы можно было перехватить исключение. Каждый блок try должен иметь как минимум один соответствующий ему блок catch или finally:

try {
    // код который может выбросить исключение
    if (rand(0, 1)) {
        throw new Exception('One')
    } else {
        echo 'Zero';
    }
} catch (Exception $e) {
    // код который может обработать исключение
    echo $e->getMessage();
}

В каких случаях стоит применять исключения:

  • если в рамках одного метода/функции происходит несколько операций которые могут завершиться неудачей
  • если используемый вами фреймверк или библиотека декларируют их использование

Для иллюстрации первого сценария возьмём уже озвученный пример функции для записи данных в файл – помешать нам может очень много факторов, а для того, чтобы сообщить выше стоящему коду в чем именно была проблема необходимо создать и выбросить исключение:

$directory = __DIR__ . DIRECTORY_SEPARATOR . 'logs';

// директории может не быть
if (!is_dir($directory)) {
    throw new Exception('Directory `logs` is not exists');
}

// может не быть прав на запись в директорию
if (!is_writable($directory)) {
    throw new Exception('Directory `logs` is not writable');
}

// возможно кто-то уже создал файл, и закрыл к нему доступ
if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
    throw new Exception('System can't create log file');
}

fputs($file, date('[H:i:s]') . " donen");
fclose($file);

Соответственно ловить данные исключения будем примерно так:

try {
    // код который пишет в файл
    // ...
} catch (Exception $e) {
    // выводим текст ошибки
    echo 'Не получилось: '. $e->getMessage();
}

В данном примере приведен очень простой сценарий обработки исключений, когда у нас любая исключительная ситуация обрабатывается на один манер. Но зачастую – различные исключения требуют различного подхода к обработке, и тогда следует использовать коды исключений и задать иерархию исключений в приложении:

// исключения файловой системы
class FileSystemException extends Exception {}

// исключения связанные с директориями
class DirectoryException extends FileSystemException {
    // коды исключений
    const DIRECTORY_NOT_EXISTS =  1;
    const DIRECTORY_NOT_WRITABLE = 2;
}

// исключения связанные с файлами
class FileException extends FileSystemException {}

Теперь, если использовать эти исключения то можно получить следующий код:

try {
    // код который пишет в файл
    if (!is_dir($directory)) {
        throw new DirectoryException('Directory `logs` is not exists', DirectoryException::DIRECTORY_NOT_EXISTS);
    }

    if (!is_writable($directory)) {
        throw new DirectoryException('Directory `logs` is not writable', DirectoryException::DIRECTORY_NOT_WRITABLE);
    }

    if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
        throw new FileException('System can't open log file');
    }

    fputs($file, date('[H:i:s]'') . " donen");
    fclose($file);
} catch (DirectoryException $e) {
    echo 'С директорией возникла проблема: '. $e->getMessage();
} catch (FileException $e) {
    echo 'С файлом возникла проблема: '. $e->getMessage();
} catch (FileSystemException $e) {
    echo 'Ошибка файловой системы: '. $e->getMessage();
} catch (Exception $e) {
    echo 'Ошибка сервера: '. $e->getMessage();
}

Важно помнить, что Exception — это прежде всего исключительное событие, иными словами исключение из правил. Не нужно использовать их для обработки очевидных ошибок, к примеру, для валидации введённых пользователем данных (хотя тут не всё так однозначно). При этом обработчик исключений должен быть написан в том месте, где он будет способен его обработать. К примеру, обработчик для исключений вызванных недоступностью файла для записи должен быть в методе, который отвечает за выбор файла или методе его вызывающем, для того что бы он имел возможность выбрать другой файл или другую директорию.

Так, а что будет если не поймать исключение? Вы получите “Fatal Error: Uncaught exception …”. Неприятно.
Чтобы избежать подобной ситуации следует использовать функцию set_exception_handler() и установить обработчик для исключений, которые брошены вне блока try-catch и не были обработаны. После вызова такого обработчика выполнение скрипта будет остановлено:

// в качестве обработчика событий 
// будем использовать анонимную функцию
set_exception_handler(function($exception) {
    /** @var Exception $exception */
    echo $exception->getMessage(), "<br/>n";
    echo $exception->getFile(), ':', $exception->getLine(), "<br/>n";
    echo $exception->getTraceAsString(), "<br/>n";
});

Ещё расскажу про конструкцию с использованием блока finally – этот блок будет выполнен вне зависимости от того, было выброшено исключение или нет:

try {
    // код который может выбросить исключение
} catch (Exception $e) {
    // код который может обработать исключение
    // если конечно оно появится
} finally {
    // код, который будет выполнен при любом раскладе
}

Для понимания того, что это нам даёт приведу следующий пример использования блока finally:

try {
    // где-то глубоко внутри кода
    // соединение с базой данных
    $handler = mysqli_connect('localhost', 'root', '', 'test');

    try {
        // при работе с БД возникла исключительная ситуация
        // ...
        throw new Exception('DB error');
    } catch (Exception $e) {
        // исключение поймали, обработали на своём уровне
        // и должны его пробросить вверх, для дальнейшей обработки
        throw new Exception('Catch exception', 0, $e);
    } finally {
        // но, соединение с БД необходимо закрыть
        // будем делать это в блоке finally
        mysqli_close($handler);
    }

    // этот код не будет выполнен, если произойдёт исключение в коде выше
    echo "Ok";
} catch (Exception $e) {
    // ловим исключение, и выводим текст
    echo $e->getMessage();
    echo "<br/>";
    // выводим информацию о первоначальном исключении
    echo $e->getPrevious()->getMessage();
}

Т.е. запомните – блок finally будет выполнен даже в том случае, если вы в блоке catch пробрасываете исключение выше (собственно именно так он и задумывался).

Для вводной статьи информации в самый раз, кто жаждет ещё подробностей, то вы их найдёте в статье Исключительный код 😉

Задание
Написать свой обработчик исключений, с выводом текста файла где произошла ошибка, и всё это с подсветкой синтаксиса, так же не забудьте вывести trace в читаемом виде. Для ориентира – посмотрите как это круто выглядит у whoops.

PHP7 – всё не так, как было раньше

Так, вот вы сейчас всю информацию выше усвоили и теперь я буду грузить вас нововведениями в PHP7, т.е. я буду рассказывать о том, с чем вы столкнётесь через год работы PHP разработчиком. Ранее я вам рассказывал и показывал на примерах какой костыль нужно соорудить, чтобы отлавливать критические ошибки, так вот – в PHP7 это решили исправить, но как обычно завязались на обратную совместимость кода, и получили хоть и универсальное решение, но оно далеко от идеала. А теперь по пунктам об изменениях:

  1. при возникновении фатальных ошибок типа E_ERROR или фатальных ошибок с возможностью обработки E_RECOVERABLE_ERROR PHP выбрасывает исключение
  2. эти исключения не наследуют класс Exception (помните я говорил об обратной совместимости, это всё ради неё)
  3. эти исключения наследуют класс Error
  4. оба класса Exception и Error реализуют интерфейс Throwable
  5. вы не можете реализовать интерфейс Throwable в своём коде

Интерфейс Throwable практически полностью повторяет нам Exception:

interface Throwable
{
    public function getMessage(): string;
    public function getCode(): int;
    public function getFile(): string;
    public function getLine(): int;
    public function getTrace(): array;
    public function getTraceAsString(): string;
    public function getPrevious(): Throwable;
    public function __toString(): string;
}

Сложно? Теперь на примерах, возьмём те, что были выше и слегка модернизируем:

try {
    // файл, который вызывает ошибку парсера
    include 'e_parse_include.php';
} catch (Error $e) {
    var_dump($e);
}

В результате ошибку поймаем и выведем:

object(ParseError)#1 (7) {
  ["message":protected] => string(48) "syntax error, unexpected 'будет' (T_STRING)"
  ["string":"Error":private] => string(0) ""
  ["code":protected] => int(0)
  ["file":protected] => string(49) "/www/education/error/e_parse_include.php"
  ["line":protected] => int(4)
  ["trace":"Error":private] => array(0) { }
  ["previous":"Error":private] => NULL
}

Как видите – поймали исключение ParseError, которое является наследником исключения Error, который реализует интерфейс Throwable, в доме который построил Джек. Ещё есть другие, но не буду мучать – для наглядности приведу иерархию исключений:

interface Throwable
  |- Exception implements Throwable
  |    |- ErrorException extends Exception
  |    |- ... extends Exception
  |    `- ... extends Exception
  `- Error implements Throwable
      |- TypeError extends Error
      |- ParseError extends Error
      |- ArithmeticError extends Error
      |  `- DivisionByZeroError extends ArithmeticError
      `- AssertionError extends Error 

TypeError – для ошибок, когда тип аргументов функции не совпадает с передаваемым типом:

try {
    (function(int $one, int $two) {
        return;
    })('one', 'two');
} catch (TypeError $e) {
    echo $e->getMessage();
}

ArithmeticError – могут возникнуть при математических операциях, к примеру когда результат вычисления превышает лимит выделенный для целого числа:

try {
    1 << -1;
} catch (ArithmeticError $e) {
    echo $e->getMessage();
}

DivisionByZeroError – ошибка деления на ноль:

try {
    1 / 0;
} catch (ArithmeticError $e) {
    echo $e->getMessage();
}

AssertionError – редкий зверь, появляется когда условие заданное в assert() не выполняется:

ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);

try {
    assert(1 === 0);
} catch (AssertionError $e) {
    echo $e->getMessage();
}

При настройках production-серверов, директивы zend.assertions и assert.exception отключают, и это правильно

Задание
Написать универсальный обработчик ошибок для PHP7, который будет отлавливать все возможные исключения.

При написании данного раздела были использованы материалы из статьи Throwable Exceptions and Errors in PHP 7

Отладка

Иногда для отладки кода нужно отследить что происходило с переменной или объектом на определённом этапе, для этих целей есть функция debug_backtrace() и debug_print_backtrace() которые вернут историю вызовов функций/методов в обратном порядке:

<?php
function example() {
    echo '<pre>';
    debug_print_backtrace();
    echo '</pre>';
}

class ExampleClass {
    public static function method () {
        example();
    }
}

ExampleClass::method();

В результате выполнения функции debug_print_backtrace() будет выведен список вызовов приведших нас к данной точке:

#0  example() called at [/www/education/error/backtrace.php:10]
#1  ExampleClass::method() called at [/www/education/error/backtrace.php:14]

Проверить код на наличие синтаксических ошибок можно с помощью функции php_check_syntax() или же команды php -l [путь к файлу], но я не встречал использования оных.

Assert

Отдельно хочу рассказать о таком экзотическом звере как assert() в PHP, собственно это кусочек контрактной методологии программирования, и дальше я расскажу вам как я никогда его не использовал 🙂

Первый случай – это когда вам надо написать TODO прямо в коде, да так, чтобы точно не забыть реализовать заданный функционал:

// включаем вывод ошибок
error_reporting(E_ALL);
ini_set('display_errors', 1);

// включаем asserts
ini_set('zend.assertions', 1);
ini_set('assert.active', 1);

assert(false, "Remove it!");

В результате выполнения данного кода получим E_WARNING:

Warning: assert(): Remove it! failed

PHP7 можно переключить в режим exception, и вместо ошибки будет всегда появляться исключение AssertionError:

// включаем asserts
ini_set('zend.assertions', 1);
ini_set('assert.active', 1);
// переключаем на исключения
ini_set('assert.exception', 1);

assert(false, "Remove it!");

В результате ожидаемо получаем не пойманный AssertionError. При необходимости, можно выбрасывать произвольное исключение:

assert(false, new Exception("Remove it!"));

Но я бы рекомендовал использовать метки @TODO, современные IDE отлично с ними работают, и вам не нужно будет прикладывать дополнительные усилия и ресурсы для работы с ними

Второй вариант использования – это создание некоего подобия TDD, но помните – это лишь подобие. Хотя, если сильно постараться, то можно получить забавный результат, который поможет в тестировании вашего кода:

// callback-функция для вывода информации в браузер
function backlog($script, $line, $code, $message) {
    echo "<h3>$message</h3>";
    highlight_string ($code);
}

// устанавливаем callback-функцию
assert_options(ASSERT_CALLBACK, 'backlog');
// отключаем вывод предупреждений
assert_options(ASSERT_WARNING,  false);

// пишем проверку и её описание
assert("sqr(4) == 16", "When I send integer, function should return square of it");

// функция, которую проверяем
function sqr($a) {
    return; // она не работает
}

Третий теоретический вариант – это непосредственно контрактное программирование – когда вы описали правила использования своей библиотеки, но хотите точно убедится, что вас поняли правильно, и в случае чего сразу указать разработчику на ошибку (я вот даже не уверен, что правильно его понимаю, но пример кода вполне рабочий):

/**
 * Настройки соединения должны передаваться в следующем виде
 *
 *     [
 *         'host' => 'localhost',
 *         'port' => 3306,
 *         'name' => 'dbname',
 *         'user' => 'root',
 *         'pass' => ''
 *     ]
 *
 * @param $settings
 */
function setupDb ($settings) {
    // проверяем настройки
    assert(isset($settings['host']), 'Db `host` is required');
    assert(isset($settings['port']) && is_int($settings['port']), 'Db `port` is required, should be integer');
    assert(isset($settings['name']), 'Db `name` is required, should be integer');

    // соединяем с БД
    // ...
}

setupDb(['host' => 'localhost']);

Никогда не используйте assert() для проверки входных параметров, ведь фактически assert() интерпретирует строковую переменную (ведёт себя как eval()), а это чревато PHP-инъекцией. И да, это правильное поведение, т.к. просто отключив assert’ы всё что передаётся внутрь будет проигнорировано, а если делать как в примере выше, то код будет выполняться, а внутрь отключенного assert’a будет передан булевый результат выполнения

Если у вас есть живой опыт использования assert() – поделитесь со мной, буду благодарен. И да, вот вам ещё занимательно чтива по этой теме – PHP Assertions, с таким же вопросом в конце 🙂

В заключение

Я за вас напишу выводы из данной статьи:

  • Ошибкам бой – их не должно быть в вашем коде
  • Используйте исключения – работу с ними нужно правильно организовать и будет счастье
  • Assert – узнали о них, и хорошо

P.S. Спасибо Максиму Слесаренко за помощь в написании статьи

By definition, syntax is an arrangement of elements such as words or a set of rules that determine the form of a structure. Thus, if there’s an element in your code that is not part of the syntax like an extra comma or if it’s missing an element that is supposed to be in the code like a missing bracket, the compiler will not be able to parse or process the file, and most likely to generate an error.

A syntax error appears when the ‘syntax’ of the rules are not followed correctly. It happens when the written code is not correct. For instance, there’s a missing semicolon, a misspelled word, or an additional bracket. Mistakes as simple as these can make the system lost in translation, but on the brighter side, these errors indicate where the issue comes from and how to solve it. For those who run multiple WordPress websites, you can monitor user activities in the WordPress dashboard to locate which user activity caused the error.

Also, keep in mind that WordPress websites may experience such issues without sending any notification to the user. To make yourself aware of any errors generated in your WordPress site, make sure that your WordPress error debug is always enabled.

The structure of a syntax error usually looks like this, “Parse error: syntax error, unexpected character in path/to/php-file.php on line number“; whereas undefined constant errors are structured like this, “Notice: Use of undefined constant constant string – assumed ‘constant string‘ in path/to/php-file.php on line number“. An example of an unexpected error is this, “Parse error: unexpected character in path/to/php-file.php on line number“.

The word ‘number’ refers to the line number written in nominal form like 25 or 1345 for instance. The ‘file’ tells you where the issue persists, the ‘line number’ hints you where the error is located, while the ‘character’ or the ‘constant string’ provides a clue on what to find exactly around the stated line number. Unexpected parse errors may also list a string instead of a character.

What Causes the PHP Parse or Syntax Errors In WordPress?

За последние 24 часа нас посетили 8750 программистов и 848 роботов. Сейчас ищут 279 программистов …


  1. prog

    С нами с:
    2 авг 2017
    Сообщения:
    5
    Симпатии:
    0

    Выдаётся ошибка, не могу найти ошибку.
    syntax error, unexpected ‘{‘ in X:homelocalhostwwwmigrantadd_list_migrants.php on line 52

    1. include («blocks/bd.php»);
    2. if (isset($_POST[‘m_reg_date’]))           {$m_reg_date = $_POST            [‘m_reg_date’];}
    3. if (isset($_POST[‘m_surname’]))            {$m_surname = $_POST             [‘m_surname’];}
    4. if (isset($_POST[‘m_name’]))               {$m_name = $_POST                [‘m_name’];}
    5. if (isset($_POST[‘m_fathername’]))         {$m_fathername = $_POST          [‘m_fathername’];}
    6. if (isset($_POST[‘m_sex’]))                {$m_sex = $_POST                 [‘m_sex’];}
    7. if (isset($_POST[‘m_dob’]))                {$m_dob = $_POST                 [‘m_dob’];}
    8. if (isset($_POST[‘m_nation’]))             {$m_nation = $_POST              [‘m_nation’];}
    9. if (isset($_POST[‘m_pass_number’]))        {$m_pass_number = $_POST         [‘m_pass_number’];}
    10. if (isset($_POST[‘m_pass_date’]))          {$m_pass_date = $_POST           [‘m_pass_date’];}
    11. if (isset($_POST[‘m_pass_issued’]))        {$m_pass_issued = $_POST         [‘m_pass_issued’];}
    12. if (isset($_POST[‘m_address’]))            {$m_address = $_POST             [‘m_address’];}
    13. if (isset($_POST[‘m_edu_lavel’]))          {$m_edu_lavel = $_POST           [‘m_edu_lavel’];}
    14. if (isset($_POST[‘m_jamoat’]))             {$m_jamoat = $_POST              [‘m_jamoat’];}
    15. if (isset($_POST[‘m_date_leave’]))         {$m_date_leave = $_POST          [‘m_date_leave’];}
    16. if (isset($_POST[‘m_date_arrival’]))       {$m_date_arrival = $_POST        [‘m_date_arrival’];}
    17. if (isset($_POST[‘m_date_worck_start’]))   {$m_date_worck_start = $_POST    [‘m_date_worck_start’];}
    18. if (isset($_POST[‘m_date_worck_end’]))     {$m_date_worck_end = $_POST      [‘m_date_worck_end’];}
    19. <!DOCTYPE HTML PUBLIC «-//W3C//DTD HTML 4.01 Transitional//EN» «[URL]http://www.w3.org/TR/html4/loose.dtd[/URL]»>
    20. <meta http-equiv=»Content-Type» content=»text/html; charset=utf-8″>
    21. <title>Обработчик</title>
    22. <link href=»style.css» rel=»stylesheet» type=»text/css»>
    23. <table width=»690″ align=»center» bordercolor=»#FFFFFF» bgcolor=»#FFFFFF» class=»main_border»>
    24. <!—Подключаем шапку сайта—>
    25. <? include («blocks/header.php»);?>
    26.       <!—Подключаем левый блок сайта—>
    27.         <? include («blocks/lefttd.php»)?>
    28. /*Здесь пишем что можно заносить информацию в базу*/
    29. $result = mysql_query («INSERT INTO migrant_list(m_reg_date,m_surname,m_name,m_fathername,m_sex,m_dob,m_nation,m_pass_number,m_pass_date, m_pass_issued,m_address,m_edu_lavel,m_jamoat,m_date_leave,m_date_arrival,m_date_worck_start,m_date_worck_end) VALUES (‘$m_reg_date‘, ‘$m_surname‘, ‘$m_name‘, ‘$m_fathername‘, ‘$m_sex‘, ‘$m_dob‘, ‘$m_nation‘, ‘$m_pass_number‘, ‘$m_pass_date‘, ‘$m_pass_issued‘, ‘$m_address‘, ‘$m_edu_lavel‘, ‘$m_jamoat‘, ‘$m_date_leave‘, ‘$m_date_arrival‘, ‘$m_date_worck_start‘, ‘$m_date_worck_end‘)»);
    30. if ($result == ‘true’) {echo «<p>Ваши данные успешно добавлены!</p>»;}
    31. else {echo «<p>Ваши данные не добавлены!</p>»;}
    32. echo «<p> Вы ввели не всю информацию поэтому данные в базу не могут быть добавлены.</p>»;
    33.   <!—Подключаем нижную часть сайта—>
    34.    <?  include («blocks/footer.php»)?>


  2. artoodetoo

    Команда форума
    Модератор

    С нами с:
    11 июн 2010
    Сообщения:
    10.818
    Симпатии:
    1.171
    Адрес:
    там-сям

    Я отредактировал твоё сообщение: вынес его из чужой темы и заменил, сцуко, ббкод [ b ] на [ php ]
    теперь видно и синтаксис, и номера строк. Так ведь лучше, правда?
    — Добавлено —
    Ошибка «unexpected… траляляля» означает, что ты что-то сделал неправильно ДО указанного места. Пропустил точку с запятой или скобки непарные.

    Чувак, на каждую открывающую скобку должна быть одна закрывающая. В твоём случае, в строке 49 перед каждым isset ты тупо накопировал открывающую скобку. поэтому фигурная скобка случилась в неожиданном (unexpected) для PHP месте.


  3. prog

    С нами с:
    2 авг 2017
    Сообщения:
    5
    Симпатии:
    0


  4. artoodetoo

    Команда форума
    Модератор

    С нами с:
    11 июн 2010
    Сообщения:
    10.818
    Симпатии:
    1.171
    Адрес:
    там-сям


  5. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    А еще в isset можно через запятую передавать переменные..


  6. TeslaFeo

    С нами с:
    9 мар 2016
    Сообщения:
    2.993
    Симпатии:
    759

    1. foreach ( $_POST as $k => $v ) {


  7. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    Ну, раз пошла такая пьянка, то можно сделать проще:


    Васяня и TeslaFeo нравится это.


  8. MouseZver

    С нами с:
    1 апр 2013
    Сообщения:
    7.561
    Симпатии:
    1.284
    Адрес:
    Лень

    filter_input_array
    — Добавлено —

    а дальше через иссет все переменные дергаем, тобишь снова говнокод


  9. prog

    С нами с:
    2 авг 2017
    Сообщения:
    5
    Симпатии:
    0

    как ставит код чтоб было видно

    как ставит код чтоб было видно синтаксис, и номера строк?


  10. prog

    С нами с:
    2 авг 2017
    Сообщения:
    5
    Симпатии:
    0

    выдает сообщение что данные обновились, но после обновления главной страницы изменения не сохранились.

    1. include («blocks/bd.php»);
    2. if (isset($_POST[‘m_reg_date’]))        {$m_reg_date = $_POST       [‘m_reg_date’];          if ($m_reg_date == ») {unset ($m_reg_date);}}  
    3. if (isset($_POST[‘m_surname’]))         {$m_surname = $_POST        [‘m_surname’];          if ($m_surname == ») {unset ($m_surname);}}
    4. if (isset($_POST[‘m_name’]))            {$m_name = $_POST           [‘m_name’];             if ($m_name == ») {unset ($m_name);}}
    5. if (isset($_POST[‘m_fathername’]))      {$m_fathername = $_POST     [‘m_fathername’];       if ($m_fathername == ») {unset ($m_fathername);}}
    6. if (isset($_POST[‘m_sex’]))             {$m_sex = $_POST            [‘m_sex’];             if ($m_sex == ») {unset ($m_sex);}}
    7. if (isset($_POST[‘m_dob’]))             {$m_dob = $_POST            [‘m_dob’];              if ($m_dob == ») {unset ($m_dob);}}
    8. if (isset($_POST[‘m_nation’]))          {$m_nation = $_POST         [‘m_nation’];           if ($m_nation == ») {unset ($m_nation);}}
    9. if (isset($_POST[‘m_pass_number’]))     {$m_pass_number = $_POST    [‘m_pass_number’];      if ($m_pass_number == ») {unset ($m_pass_number);}}
    10. if (isset($_POST[‘m_pass_date’]))       {$m_pass_date = $_POST      [‘m_pass_date’];        if ($m_pass_date == ») {unset ($m_pass_date);}}
    11. if (isset($_POST[‘m_pass_issued’]))     {$m_pass_issued = $_POST    [‘m_pass_issued’];      if ($m_pass_issued == ») {unset ($m_pass_issued);}}
    12. if (isset($_POST[‘m_address’]))         {$m_address = $_POST        [‘m_address’];          if ($m_address == ») {unset ($m_address);}}
    13. if (isset($_POST[‘m_edu_lavel’]))       {$m_edu_lavel = $_POST      [‘m_edu_lavel’];        if ($m_edu_lavel == ») {unset ($m_edu_lavel);}}
    14. if (isset($_POST[‘m_jamoat’]))          {$m_jamoat = $_POST         [‘m_jamoat’];           if ($m_jamoat == ») {unset ($m_jamoat);}}
    15. if (isset($_POST[‘m_date_leave’]))      {$m_date_leave = $_POST     [‘m_date_leave’];       if ($m_date_leave == ») {unset ($m_date_leave);}}
    16. if (isset($_POST[‘m_date_arrival’]))    {$m_date_arrival = $_POST   [‘m_date_arrival’];  if ($m_date_arrival == ») {unset ($m_date_arrival);}}
    17. if (isset($_POST[‘m_date_worck_start’])){$m_date_worck_start = $_POST[‘m_date_worck_start’]; if ($m_date_worck_start == ») {unset ($m_date_worck_start);}}
    18. if (isset($_POST[‘m_date_worck_end’]))  {$m_date_worck_end = $_POST [‘m_date_worck_end’]; if ($m_date_worck_end == »){unset ($m_date_worck_end);}}
    19. if (isset($_POST[‘id’]))                {$id = $_POST [‘id’];}
    20. <!DOCTYPE HTML PUBLIC «-//W3C//DTD HTML 4.01 Transitional//EN» «http://www.w3.org/TR/html4/loose.dtd»>
    21. <meta http-equiv=»Content-Type» content=»text/html; charset=utf-8″>
    22. <title>Обработчик</title>
    23. <link href=»style.css» rel=»stylesheet» type=»text/css»>
    24. <table width=»690″ align=»center» bordercolor=»#FFFFFF» bgcolor=»#FFFFFF» class=»main_border»>
    25. <!—Подключаем шапку сайта—>
    26. <? include («blocks/header.php»);?>
    27.       <!—Подключаем левый блок сайта—>
    28.         <? include («blocks/lefttd.php»)?>
    29. /*Здесь пишем что можно заносить информацию в базу*/
    30. m_reg_date=’$m_reg_date‘, m_surname=’$m_surname‘, m_name=’$m_name‘, m_fathername=’$m_fathername‘, m_sex=’$m_sex‘, m_dob=’$m_dob‘, m_nation=’$m_nation‘, m_pass_number=’$m_pass_number‘, m_pass_date=’$m_pass_date‘, m_pass_issued=’$m_pass_issued‘, m_address=’$m_address‘,
    31. m_edu_lavel=’$m_edu_lavel‘, m_jamoat=’$m_jamoat‘, m_date_leave=’$m_date_leave‘, m_date_arrival=’$m_date_arrival‘,
    32. m_date_worck_start=’$m_date_worck_start‘, m_date_worck_end=’$m_date_worck_end‘ WHERE id=’$id‘»);
    33. if ($result == ‘true’) {echo «<p>Данные успешно обновлены!</p>»;}
    34. else {echo «<p>Данные не обновлены!</p>»;}
    35. echo «<p> Вы ввели не всю информацию поэтому данные в базу не могут быть обновлены.</p>»;
    36.   <!—Подключаем нижную часть сайта—>
    37.    <?  include («blocks/footer.php»)?>


  11. MouseZver

    С нами с:
    1 апр 2013
    Сообщения:
    7.561
    Симпатии:
    1.284
    Адрес:
    Лень

    Дерьмо а не код
    — Добавлено —
    прочти про фильтры , не игнорь бл* посты


  12. prog

    С нами с:
    2 авг 2017
    Сообщения:
    5
    Симпатии:
    0

    и именно после WHERE id=’$id’ обновления не происходит, без WHERE id=’$id’ обновления происходить но во всех данных, к примеру если мы изменяем какую та фамилию то это фамилия присваивается к другим фамилиям.
    Нужна Ваша помощь.


  13. xaker01

    xaker01
    Активный пользователь

    С нами с:
    16 апр 2016
    Сообщения:
    210
    Симпатии:
    34

    Для начало код приводить в читабельный вид. хотя это сложно назвать читабельным тоже.

    1. include («blocks/bd.php»);
    2. if (isset($_POST[‘m_reg_date’])) {
    3.     $m_reg_date = $_POST [‘m_reg_date’];
    4. if (isset($_POST[‘m_surname’])) {
    5.     $m_surname = $_POST [‘m_surname’];
    6. if (isset($_POST[‘m_name’])) {
    7.     $m_name = $_POST [‘m_name’];
    8. if (isset($_POST[‘m_fathername’])) {
    9.     $m_fathername = $_POST [‘m_fathername’];
    10.     if ($m_fathername == ») {
    11. if (isset($_POST[‘m_sex’])) {
    12.     $m_sex = $_POST [‘m_sex’];
    13. if (isset($_POST[‘m_dob’])) {
    14.     $m_dob = $_POST [‘m_dob’];
    15. if (isset($_POST[‘m_nation’])) {
    16.     $m_nation = $_POST [‘m_nation’];
    17. if (isset($_POST[‘m_pass_number’])) {
    18.     $m_pass_number = $_POST [‘m_pass_number’];
    19.     if ($m_pass_number == ») {
    20. if (isset($_POST[‘m_pass_date’])) {
    21.     $m_pass_date = $_POST [‘m_pass_date’];
    22.     if ($m_pass_date == ») {
    23. if (isset($_POST[‘m_pass_issued’])) {
    24.     $m_pass_issued = $_POST [‘m_pass_issued’];
    25.     if ($m_pass_issued == ») {
    26. if (isset($_POST[‘m_address’])) {
    27.     $m_address = $_POST [‘m_address’];
    28. if (isset($_POST[‘m_edu_lavel’])) {
    29.     $m_edu_lavel = $_POST [‘m_edu_lavel’];
    30.     if ($m_edu_lavel == ») {
    31. if (isset($_POST[‘m_jamoat’])) {
    32.     $m_jamoat = $_POST [‘m_jamoat’];
    33. if (isset($_POST[‘m_date_leave’])) {
    34.     $m_date_leave = $_POST [‘m_date_leave’];
    35.     if ($m_date_leave == ») {
    36. if (isset($_POST[‘m_date_arrival’])) {
    37.     $m_date_arrival = $_POST [‘m_date_arrival’];
    38.     if ($m_date_arrival == ») {
    39. if (isset($_POST[‘m_date_worck_start’])) {
    40.     $m_date_worck_start = $_POST[‘m_date_worck_start’];
    41.     if ($m_date_worck_start == ») {
    42.         unset($m_date_worck_start);
    43. if (isset($_POST[‘m_date_worck_end’])) {
    44.     $m_date_worck_end = $_POST [‘m_date_worck_end’];
    45.     if ($m_date_worck_end == ») {
    46.         unset($m_date_worck_end);
    47. if (isset($_POST[‘id’])) {
    48. <!DOCTYPE HTML PUBLIC «-//W3C//DTD HTML 4.01 Transitional//EN» «http://www.w3.org/TR/html4/loose.dtd»>
    49.         <meta http-equiv=»Content-Type» content=»text/html; charset=utf-8″>
    50.         <title>Обработчик</title>
    51.         <link href=»style.css» rel=»stylesheet» type=»text/css»>
    52.         <table width=»690″ align=»center» bordercolor=»#FFFFFF» bgcolor=»#FFFFFF» class=»main_border»>
    53.             <!—Подключаем шапку сайта—>
    54. <? include («blocks/header.php»); ?>
    55.                             <!—Подключаем левый блок сайта—>
    56. <? include («blocks/lefttd.php») ?>
    57.     /* Здесь пишем что можно заносить информацию в базу */
    58. m_reg_date=’$m_reg_date‘, m_surname=’$m_surname‘, m_name=’$m_name‘, m_fathername=’$m_fathername‘, m_sex=’$m_sex‘, m_dob=’$m_dob‘, m_nation=’$m_nation‘, m_pass_number=’$m_pass_number‘, m_pass_date=’$m_pass_date‘, m_pass_issued=’$m_pass_issued‘, m_address=’$m_address‘,
    59. m_edu_lavel=’$m_edu_lavel‘, m_jamoat=’$m_jamoat‘, m_date_leave=’$m_date_leave‘, m_date_arrival=’$m_date_arrival‘,
    60. m_date_worck_start=’$m_date_worck_start‘, m_date_worck_end=’$m_date_worck_end‘ WHERE id=’$id‘»);
    61.         echo «<p>Данные успешно обновлены!</p>»;
    62.         echo «<p>Данные не обновлены!</p>»;
    63.     echo «<p> Вы ввели не всю информацию поэтому данные в базу не могут быть обновлены.</p>»;
    64.                 <!—Подключаем нижную часть сайта—>
    65. <? include («blocks/footer.php») ?>

    Далее с 1 по 109 строчку сокрашаем до 10 максимум строчек.
    Выше тебе уже написали как.

    Далее строчки начиная с 133

    1.     /* Здесь пишем что можно заносить информацию в базу */

    Опять укоротить.
    И смотреть в сторону mysqli/pdo . С подготовленными запросами.

    И тогда уже может не прийдется помогать, или помочь уже будет намного легче

Содержание

  1. PHP Parse error: syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE) in laravel/framework/src/Illuminate/Foundation/helpers.php on line 476 #16674
  2. Comments
  3. Description:
  4. Steps To Reproduce:
  5. parsing — PHP parse/syntax errors; and how to solve them
  6. Answer
  7. Solution:
  8. What are the syntax errors?
  9. Most important tips
  10. How to interpret parser errors
  11. Solving syntax errors
  12. White screen of death
  13. Answer
  14. Solution:
  15. Using a syntax-checking IDE means:
  16. Answer
  17. Solution:
  18. Unexpected <-code-11>-code-1>
  19. Unexpected <-code-21>closing square bracket
  20. Answer
  21. Solution:
  22. Unexpected An &quot<-code-13<-code-16>unexpected <-code-1<-code-16>&quot <-code-13<-code-16>means that there’s a literal <-code-2<-code-16>name <-code-8<-code-16>which doesn’t fit into the current expression/statement structure Missing semicolon It most commonly indicates a missing semicolon in the previous line <-code-4<-code-16>Variable assignments following a statement are a good indicator where to look: String concatenation Btw <-code-8<-code-16>you should prefer string interpolation <-code-23>basic variables in double quotes) whenever that helps readability <-code-4<-code-16>Which avoids these syntax issues String interpolation is a scripting language core feature <-code-4<-code-16>No shame in utilizing it <-code-4<-code-16>Ignore any micro-optimization advise about variable <-code-4<-code-16>concatenation being faster <-code-4<-code-16>It’s not Missing expression operators Of course the same issue can arise in other expressions <-code-8<-code-16> <-code-14<-code-16>instance arithmetic operations: PHP can’t guess here <-code-19>the variable should have been added <-code-8<-code-16>subtracted or compared etc Lists Or functions parameter <-code-11<-code-16>s: Class declarations This parser error also occurs in class declarations <-code-4<-code-16>You can only assign static constants <-code-8<-code-16>not expressions <-code-4<-code-16>Thus the parser complains about variables as assigned data: Unmatched <-code-16>closing curly braces can in particular lead here <-code-4<-code-16>If a method is terminated too early <-code-23>use proper indentation!) <-code-8<-code-16>then a stray variable is commonly misplaced into the class declaration body Variables after ident<-code-19>iers Take in mind that using variable variables should be the exception <-code-4<-code-16>Newcomers often try to use them too casually <-code-8<-code-16>even when arrays would be simpler and more appropriate Missing parentheses after language constructs Hasty typing may lead to <-code-14<-code-16>gotten opening or closing parenthesis <-code-14<-code-16> <-code-19>and <-code-14<-code-16>and <-code-14<-code-16>each statements: Solution: add the missing opening <-code-23>between statement and variable The curly < brace does not open the code block<-code-8<-code-16>without closing the <-code-19>expression with the ) closing parenthesis first Else does not expect conditions Solution: Remove the conditions from else or use Need brackets <-code-14<-code-16>closure Solution: Add brackets around $var Invisible whitespace As mentioned in the reference answer on &quot<-code-13<-code-16>Invisible stray Unicode&quot <-code-13<-code-16><-code-23>such as a non-breaking space) <-code-8<-code-16>you might also see this error <-code-14<-code-16>unsuspecting code like: It’s rather prevalent in the start of files and <-code-14<-code-16>copy-and-pasted code <-code-4<-code-16>Check with a hexeditor <-code-8<-code-16> <-code-19>your code does not visually appear to contain a syntax issue See also Answer Solution: Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_ENCAPSED_AND_WHITESPACE refer to quoted «string» literals. They’re used in different contexts, but the syntax issue are quite similar. T_ENCAPSED… warnings occur in double quoted string context, while T_CONSTANT… strings are often astray in plain PHP expressions or statements. Incorrect variable interpolation And it comes up most frequently for incorrect PHP variable interpolation: Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted ‘string’ , because it usually expects a literal identifier / key there. More precisely it’s valid to use PHP2-style simple syntax within double quotes for array references: Nested arrays or deeper object references however require the complex curly string expression syntax: If unsure, this is commonly safer to use. It’s often even considered more readable. And better IDEs actually use distinct syntax colorization for that. Missing concatenation If a string follows an expression, but lacks a concatenation or other operator, then you’ll see PHP complain about the string literal: While it’s obvious to you and me, PHP just can’t guess that the string was meant to be appended there. Confusing string quote enclosures The same syntax error occurs when confounding string delimiters. A string started by a single ‘ or double » quote also ends with the same. That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes. Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.) This is a good example where you shouldn’t break out of double quotes in the first place. Instead just use proper for the HTML attributesВґ quotes: While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently. Missing opening quote Here the ‘, ‘ would become a string literal after a bareword, when obviously login was meant to be a string parameter. Array lists If you miss a , comma in an array creation block, the parser will see two consecutive strings: Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting. Function parameter lists Runaway strings A common variation are quite simply forgotten string terminators: Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course. HEREDOC indentation Prior PHP 7.3, the heredoc string end delimiter can’t be prefixed with spaces: Solution: upgrade PHP or find a better hoster. See also Answer Solution: Unexpected is a bit of a misnomer. It does not refer to a quoted <-code-2>. It means a raw identifier was encountered. This can range from <-code-3>words to leftover <-code-4>or function names, forgotten unquoted strings, or any plain text. Misquoted strings This syntax error is most common for misquoted string values however. Any unescaped and stray <-code-5>or <-code-6>quote will form an invalid expression: Syntax highlighting will make such mistakes super obvious. It<-code-6>s important to remember to use backslashes for escaping <-code-33> <-code-5>double quotes, or <-code-33> <-code-6>single quotes — depending on which was used as string enclosure. For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within. Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal <-code-5>double quotes. For lengthier output, prefer multiple <-code-11>/ <-code-12>lines instead of escaping in and out. Better yet consider a HEREDOC section. Another example is using PHP entry inside HTML code generated with PHP: This happens if <-code-14>is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here Unclosed strings It<-code-6>s not just literal s which the parser may protest then. Another frequent variation is an for unquoted literal HTML. Non-programming string quotes If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren<-code-6>t what PHP expects: Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example <-code-20>is interpreted as a constant identifier. But any following text literal is then seen as a <-code-3>word/ by the parser. The missing semicolon <-code-29>again If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier: PHP just can<-code-6>t know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one <-code-22>or the other. Short open tags and <-code-23>headers in PHP scripts This is rather uncommon. But if short_open_tags are enabled, then you can<-code-6>t begin your PHP scripts with an XML declaration: Share solution ↓ Additional Information: Didn’t find the answer? Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free. Similar questions Find the answer in similar questions on our website. Write quick answer Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger. About the technologies asked in this question PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license. https://www.php.net/ Laravel Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework. https://laravel.com/ JavaScript JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet. https://www.javascript.com/ MySQL DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL. It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information. https://www.mysql.com/ HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone. https://www.w3.org/html/ Welcome to programmierfrage.com programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration. Get answers to specific questions Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve. Help Others Solve Their Issues Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge. Источник
  23. Missing semicolon
  24. String concatenation
  25. Missing expression operators
  26. Lists
  27. Class declarations
  28. Variables after ident<-code-19>iers
  29. Missing parentheses after language constructs
  30. Else does not expect conditions
  31. Need brackets <-code-14<-code-16>closure
  32. Invisible whitespace
  33. See also
  34. Answer
  35. Solution:
  36. Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE
  37. Incorrect variable interpolation
  38. Missing concatenation
  39. Confusing string quote enclosures
  40. Missing opening quote
  41. Array lists
  42. Function parameter lists
  43. Runaway strings
  44. HEREDOC indentation
  45. Answer
  46. Solution:
  47. Unexpected
  48. Misquoted strings
  49. Unclosed strings
  50. Non-programming string quotes
  51. The missing semicolon <-code-29>again
  52. Short open tags and <-code-23>headers in PHP scripts
  53. Share solution ↓
  54. Additional Information:
  55. Didn’t find the answer?
  56. Similar questions
  57. Write quick answer
  58. About the technologies asked in this question
  59. Laravel
  60. JavaScript
  61. MySQL
  62. Welcome to programmierfrage.com
  63. Get answers to specific questions
  64. Help Others Solve Their Issues

PHP Parse error: syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE) in laravel/framework/src/Illuminate/Foundation/helpers.php on line 476 #16674

  • Laravel Version: 5.3.26
  • PHP Version: PHP 5.6.28-1+deb.sury.org

Description:

I have a fresh install of Laravel everything is working on my local where I’m using PHP 5.6.22 but on my production server where I have php 5.6.28 I have this error :

[Tue Dec 06 10:40:56.435993 2016] [:error] [pid 3951] [client 213.55.176.229:38035] PHP Parse error: syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE) in vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 476

Steps To Reproduce:

install the last version of laravel with php 5.6.28

The text was updated successfully, but these errors were encountered:

Content of line 476:

Seems that your PHP version doesn’t support the splat operator, which means that it isn’t PHP5.6.

Please check the version of php running on your webserver, matches that in the console.

Ah thanks you! You are right my php cli was 5.6 but the apache version was 5.5.9

Everything is fine now

Have a nice day

Thanks. Solved it for me as well. Here’s a quick snippet for any others who may find this.

Great.
that worked for me also.

Hello. I am getting this error with php 7.1. On php 5.6.30 its works fine. 🙂

I have the same problem .. laravel 5.4 with php 7.0 or 5.6.29 doesnt works.
Any solution?
Tks

Thanks guys, I was stuck on this for so long, sannysc’s snippet worked for me on laravel 5.4 on digital ocean ubuntu 14.04 LAMP

I am having the same problem with PHP 7.0.16 too (Laravel 5.3).

Guys, just check that you’re running different PHP versions from different *nix users.

Guys check that if you are in local envirmoment and using something like MAMP that the bash profile loads the MAMP php version and not default from mac. Take a look to https://gist.github.com/irazasyed/5987693
Everytime you update mamp and your hosts php version you will need to do this.

Like vimalmistry and Sennik, I’m having the same problem with PHP 7.1.2 but working with 2 docker containers. One with nginx:1.10 and other with php:7-fpm. using laravel 5.4
When I was enabled the display_errors, I received the below message:
Parse error: syntax error, unexpected ‘$kernel’ (T_VARIABLE) in /var/www/public/index.php on line 50

Same issue here.

Have the following cron job: cd /home/user/www && php ./artisan schedule:run

This executes /usr/local/php56/bin/php artisan queue-process-listener

I’m getting the following error:

Parse error: syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE) in /home/user/www/vendor/laravel/framework/src/Illuminate/Foundatio n/helpers.php on line 477

% php -v
PHP 5.6.29 (cli) (built: Dec 9 2016 23:39:41)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

% /usr/local/php56/bin/php -v
PHP 5.6.29 (cli) (built: Dec 9 2016 23:39:41)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

Same here php7.0, laravel 5.4

Even when specifying the PHP to use (7.1.1), it produced the error.

This fixed it for me, by changing the profile to point to the MAMP 7.1.1 install, and not having to run: php composer.phar, just composer.phar

Thanks @sannysc . It Works 😀

I have also this error with php 7.1 (shows from console) and Laravel 5.4.
Check php path from your local:
$ which php
/usr/local/bin/php
Give this full path in your Crontab
* * * * * /usr/local/bin/php /Users/abhilash/my-site/artisan schedule:run >> /dev/null 2>&1

It was my first day with vagrant and laravel.
I was adding a controller with php artisan make:controller PagesController function and that was generating this error.

The issue was I was doing this from host. And host had the older version of php. I ssh’ed into the server and then ran this command again, and everything worked fine.

I hope, it will help others.

If you are using Plesk ant want to use a different PHP version you can do this: export PATH=/opt/plesk/php/7.0/bin:$PATH; php artisan key:generate (7.0 or version number of course depending on what is available on the server)

hen someone can help me out with this?
Parse error: syntax error, unexpected ‘-‘, expecting ‘]’ in /storage/ssd4/198/4185198/public_html/pr.php on line 25

im totaly new in php so pleas don’t judge me. thx

i curently have PHP version: 7.0.26

Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips

After you install php7 use this so type this into your command line so that the version changes on the shell ( export PATH=/usr/local/php71/bin:$PATH )

Hey after my research i found this working for me , replace what you have under public/.htaccess with the following

i am running ubuntu 16.04, laravel 5.6, for me, it was

sudo a2dismod php5 && sudo a2dismod php5.6 && sudo a2enmod php7.1 && sudo service apache2 restart

Where did you type that? @udoy-touhid

Laravel 5.4 require php 7.1 version for me. Lower version not working. 😀

Make sure the php version matches that on your local server. Had a similar ecounter and this should fix the issue

my php version 7.2.24 and 5.3 laravel version. any solution.?

I am facing a problem when trying to run from localhost:
I have installed PHP 7.4.7
My XAMPP folder installed in D Drive.
http://127.0.0.1:8000/ is working.
But,
http://localhost/Laravel/Laravel/public/ (Shows bellow error)

Parse error: syntax error, unexpected T_CLASS, expecting T_STRING or T_VARIABLE or ‘$’ in D:xampphtdocsLaravelLaravelpublicindex.php on line 52

At Line 52:
$kernel = $app->make(IlluminateContractsHttpKernel::class);

Источник

parsing — PHP parse/syntax errors; and how to solve them

Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it’s just part of the learning process. However, it’s often easy to interpret error messages such as:

PHP Parse error: syntax error, unexpected ‘<-code-1>‘ in index.php on line 20

The unexpected symbol isn’t always the real culprit. But the line number gives a rough idea of where to start looking.

Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.

While not every case matches the other. Yet there are some general steps to . This references summarized the common pitfalls:

Closely related references:

While Stack Overflow is also welcoming rookie coders, it’s mostly targetted at professional programming questions.

  • Answering everyone’s coding mistakes and narrow typos is considered mostly off-topic.
  • So please take the time to follow the basic steps, before posting syntax fixing requests.
  • If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.

If your browser displays error messages such as «SyntaxError: illegal character», then it’s not actually php-related, but a javascript-syntax error.

Syntax errors raised on vendor code: Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor’s requirements against your platform setup.

Answer

Solution:

What are the syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or ident<-code-18>-code-11>iers. It can<-code-18>-code-8>t guess your coding intentions.

Most important tips

There are a few basic precautions you can always take:

Use proper code indentation, or adopt any lofty coding style. Readability prevents irregularities.

Read the language reference and examples in the manual. Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected <-code-18>-code-4<-code-18>-code-5>-code-2<-code-18>-code-5>, expecting <-code-18>-code-8> <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> <-code-18>-code-8> in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as <-code-18>-code-4<-code-18>-code-5>-code-2<-code-18>-code-5> explains which symbol the parser/tokenizer couldn<-code-18>-code-8>t process finally. This isn<-code-18>-code-8>t necessarily the cause of the syntax mistake, however.

It<-code-18>-code-8>s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

Open the mentioned source file. Look at the mentioned code line.

For runaway strings and misplaced operators, this is usually where you find the culprit.

Read the line left to right and imagine what each symbol does.

More regularly you need to look at preceding lines as well.

In particular, missing <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

If <-code-18>-code-4<-code-18>-code-5> code blocks <-code-18>-code-5> are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simpl<-code-18>-code-11>y that.

Look at the syntax colorization!

Strings and variables and constants should all have d<-code-18>-code-11>ferent colors.

Operators <-code-18>-code-6> should be tinted distinct as well. Else they might be in the wrong context.

If you see string colorization extend too far or too short, then you have found an unescaped or missing closing <-code-18>-code-7> or <-code-18>-code-8> string marker.

Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone <-code-18>-code-11> it<-code-18>-code-8>s not <-code-18>-code-9> , <-code-18>-code-10> , or parentheses following an operator. Two strings/ident<-code-18>-code-11>iers directly following each other are incorrect in most contexts.

Whitespace is your friend. Follow any coding style.

Break up long lines temporarily.

You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.

Split up complex <-code-18>-code-11> statements into distinct or nested <-code-18>-code-11> conditions.

Instead of lengthy math formulas or logic chains, use temporary variables to simpl<-code-18>-code-11>y the code. (More readable = fewer errors.)

Add newlines between:

  1. The code you can easily ident<-code-18>-code-11>y as correct,
  2. The parts you<-code-18>-code-8>re unsure about,
  3. And the lines which the parser complains about.

Partitioning up long code blocks really helps to locate the origin of syntax errors.

Comment out offending code.

If you can<-code-18>-code-8>t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

When you can<-code-18>-code-8>t resolve the syntax issue, try to rewrite the commented out sections from scratch.

As a newcomer, avoid some of the confusing syntax constructs.

The ternary <-code-18>-code-13> condition operator can compact code and is useful indeed. But it doesn<-code-18>-code-8>t aid readability in all cases. Prefer plain <-code-18>-code-11> statements while unversed.

PHP<-code-18>-code-8>s alternative syntax ( <-code-18>-code-11>: / else<-code-18>-code-11>: / end<-code-18>-code-11><-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> ) is common for templates, but arguably less easy to follow than normal <-code-18>-code-4<-code-18>-code-5> code <-code-18>-code-5> blocks.

The most prevalent newcomer mistakes are:

Missing semicolons <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> for terminating statements/lines.

Mismatched string quotes for <-code-18>-code-7> or <-code-18>-code-8> and unescaped quotes within.

Forgotten operators, in particular for the string . concatenation.

Unbalanced ( parentheses ) . Count them in the reported line. Are there an equal number of them?

Don<-code-18>-code-8>t forget that solving one syntax problem can uncover the next.

If you make one issue go away, but other crops up in some code below, you<-code-18>-code-8>re mostly on the right path.

If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

Restore a backup of previously working code, <-code-18>-code-11> you can<-code-18>-code-8>t fix it.

  • Adopt a source code versioning system. You can always view a d<-code-18>-code-11>f of the broken and last working version. Which might be enlightening as to what the syntax problem is.

Invisible stray Unicode characters: In some cases, you need to use a hexeditor or d<-code-18>-code-11>ferent editor/viewer on your source. Some problems cannot be found just from looking at your code.

In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

Take care of which type of linebreaks are saved in files.

PHP just honors n newlines, not r carriage returns.

Which is occasionally an issue for MacOS users (even on OS&nbsp<-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> X for misconfigured editors).

It often only surfaces as an issue when single-line // or # comments are used. Multiline /*. */ comments do seldom disturb the parser when linebreaks get ignored.

If your syntax error does not transmit over the web: It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:

You are looking at the wrong file!

Or your code contained invisible stray Unicode (see above). You can easily find out: Just copy your code back from the web form into your text editor.

Check your PHP version. Not all syntax constructs are available on every server.

php -v for the command line interpreter

&lt<-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5>?php phpinfo()<-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> for the one invoked through the webserver.

Those aren<-code-18>-code-8>t necessarily the same. In particular when working with frameworks, you will them to match up.

Don<-code-18>-code-8>t use PHP<-code-18>-code-8>s reserved keywords as ident<-code-18>-code-11>iers for functions/methods, classes or constants.

Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren<-code-18>-code-8>t as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

White screen of death

If your website is just blank, then typically a syntax error is the cause. Enable their display with:

  • error_reporting = E_ALL
  • display_errors = 1

Enabling it within the broken script is too late because PHP can<-code-18>-code-8>t even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php :

Then invoke the failing code by accessing this wrapper script.

Answer

Solution:

I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there’s absolutely no need to search for another solution.

Using a syntax-checking IDE means:

You’ll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.

Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):

Answer

Solution:

Unexpected <-code-11>-code-1>

These days, the unexpected <-code-11>-code-1> array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support <-code-11>-code-3> .

Array function result dereferencing is likewise not available for older PHP versions:

Though, you’re always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g. <-code-11>-code-7> can be used to enable a newer runtime.

BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you’re really clingy with older + slower PHP versions.

Other causes for Unexpected <-code-11>-code-1> syntax errors

If it’s not the PHP version mismatch, then it’s oftentimes a plain typo or newcomer syntax mistake:

Confusing <-code-11>-code-1> with opening curly braces <-code-11>or parentheses <-code-12>is a common oversight.

Or trying to dereference <-code-16>ants <-code-12>before PHP 5.6 <-code-23>as arrays:

At least PHP interprets that <-code-16>as a <-code-16>ant name.

If you meant to access an array variable <-code-12>which is the typical cause here<-code-23>, then add the leading <-code-17>sigil — so it becomes a <-code-17>varname .

You are trying to use the <-code-19>keyword on a member of an associative array. This is not valid syntax:

Unexpected <-code-21>closing square bracket

This is somewhat rarer, but there are also syntax accidents with the terminating array <-code-21>bracket.

Again mismatches with <-code-23>parentheses or > curly braces are common:

Or trying to end an array where there isn’t one:

Which often occurs in multi-line and nested array declarations.

If so, use your IDE for bracket matching to find any premature <-code-21>array closure. At the very least use more spacing and newlines to narrow it down.

Answer

Solution:

Unexpected

An &quot<-code-13<-code-16>unexpected <-code-1<-code-16>&quot <-code-13<-code-16>means that there’s a literal <-code-2<-code-16>name <-code-8<-code-16>which doesn’t fit into the current expression/statement structure

Missing semicolon

It most commonly indicates a missing semicolon in the previous line <-code-4<-code-16>Variable assignments following a statement are a good indicator where to look:

String concatenation

Btw <-code-8<-code-16>you should prefer string interpolation <-code-23>basic variables in double quotes) whenever that helps readability <-code-4<-code-16>Which avoids these syntax issues

String interpolation is a scripting language core feature <-code-4<-code-16>No shame in utilizing it <-code-4<-code-16>Ignore any micro-optimization advise about variable <-code-4<-code-16>concatenation being faster <-code-4<-code-16>It’s not

Missing expression operators

Of course the same issue can arise in other expressions <-code-8<-code-16> <-code-14<-code-16>instance arithmetic operations:

PHP can’t guess here <-code-19>the variable should have been added <-code-8<-code-16>subtracted or compared etc

Lists

Or functions parameter <-code-11<-code-16>s:

Class declarations

This parser error also occurs in class declarations <-code-4<-code-16>You can only assign static constants <-code-8<-code-16>not expressions <-code-4<-code-16>Thus the parser complains about variables as assigned data:

Unmatched <-code-16>closing curly braces can in particular lead here <-code-4<-code-16>If a method is terminated too early <-code-23>use proper indentation!) <-code-8<-code-16>then a stray variable is commonly misplaced into the class declaration body

Variables after ident<-code-19>iers

Take in mind that using variable variables should be the exception <-code-4<-code-16>Newcomers often try to use them too casually <-code-8<-code-16>even when arrays would be simpler and more appropriate

Missing parentheses after language constructs

Hasty typing may lead to <-code-14<-code-16>gotten opening or closing parenthesis <-code-14<-code-16> <-code-19>and <-code-14<-code-16>and <-code-14<-code-16>each statements:

Solution: add the missing opening <-code-23>between statement and variable

The curly < brace does not open the code block<-code-8<-code-16>without closing the <-code-19>expression with the ) closing parenthesis first

Else does not expect conditions

Solution: Remove the conditions from else or use

Need brackets <-code-14<-code-16>closure

Solution: Add brackets around $var

Invisible whitespace

As mentioned in the reference answer on &quot<-code-13<-code-16>Invisible stray Unicode&quot <-code-13<-code-16><-code-23>such as a non-breaking space) <-code-8<-code-16>you might also see this error <-code-14<-code-16>unsuspecting code like:

It’s rather prevalent in the start of files and <-code-14<-code-16>copy-and-pasted code <-code-4<-code-16>Check with a hexeditor <-code-8<-code-16> <-code-19>your code does not visually appear to contain a syntax issue

See also

Answer

Solution:

Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_ENCAPSED_AND_WHITESPACE refer to quoted «string» literals.

They’re used in different contexts, but the syntax issue are quite similar. T_ENCAPSED… warnings occur in double quoted string context, while T_CONSTANT… strings are often astray in plain PHP expressions or statements.

Incorrect variable interpolation

And it comes up most frequently for incorrect PHP variable interpolation:

Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted ‘string’ , because it usually expects a literal identifier / key there.

More precisely it’s valid to use PHP2-style simple syntax within double quotes for array references:

Nested arrays or deeper object references however require the complex curly string expression syntax:

If unsure, this is commonly safer to use. It’s often even considered more readable. And better IDEs actually use distinct syntax colorization for that.

Missing concatenation

If a string follows an expression, but lacks a concatenation or other operator, then you’ll see PHP complain about the string literal:

While it’s obvious to you and me, PHP just can’t guess that the string was meant to be appended there.

Confusing string quote enclosures

The same syntax error occurs when confounding string delimiters. A string started by a single ‘ or double » quote also ends with the same.

That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes.

Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.)

This is a good example where you shouldn’t break out of double quotes in the first place. Instead just use proper for the HTML attributesВґ quotes:

While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently.

Missing opening quote

Here the ‘, ‘ would become a string literal after a bareword, when obviously login was meant to be a string parameter.

Array lists

If you miss a , comma in an array creation block, the parser will see two consecutive strings:

Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting.

Function parameter lists

Runaway strings

A common variation are quite simply forgotten string terminators:

Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course.

HEREDOC indentation

Prior PHP 7.3, the heredoc string end delimiter can’t be prefixed with spaces:

Solution: upgrade PHP or find a better hoster.

See also

Answer

Solution:

Unexpected

is a bit of a misnomer. It does not refer to a quoted <-code-2>. It means a raw identifier was encountered. This can range from <-code-3>words to leftover <-code-4>or function names, forgotten unquoted strings, or any plain text.

Misquoted strings

This syntax error is most common for misquoted string values however. Any unescaped and stray <-code-5>or <-code-6>quote will form an invalid expression:

Syntax highlighting will make such mistakes super obvious. It<-code-6>s important to remember to use backslashes for escaping <-code-33> <-code-5>double quotes, or <-code-33> <-code-6>single quotes — depending on which was used as string enclosure.

  • For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within.
  • Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal <-code-5>double quotes.
  • For lengthier output, prefer multiple <-code-11>/ <-code-12>lines instead of escaping in and out. Better yet consider a HEREDOC section.

Another example is using PHP entry inside HTML code generated with PHP:

This happens if <-code-14>is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here

Unclosed strings

It<-code-6>s not just literal s which the parser may protest then. Another frequent variation is an for unquoted literal HTML.

Non-programming string quotes

If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren<-code-6>t what PHP expects:

Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example <-code-20>is interpreted as a constant identifier. But any following text literal is then seen as a <-code-3>word/ by the parser.

The missing semicolon <-code-29>again

If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier:

PHP just can<-code-6>t know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one <-code-22>or the other.

Short open tags and <-code-23>headers in PHP scripts

This is rather uncommon. But if short_open_tags are enabled, then you can<-code-6>t begin your PHP scripts with an XML declaration:

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Laravel

Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/

JavaScript

JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/

MySQL

DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL. It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/

HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

PHP для начинающих. Обработка ошибок +32

PHP


Рекомендация: подборка платных и бесплатных курсов Java — https://katalog-kursov.ru/

image

Не совершает ошибок только тот, кто ничего не делает, и мы тому пример — сидим и трудимся не покладая рук, читаем Хабр 🙂

В этой статье я поведу свой рассказа об ошибках в PHP, и о том как их обуздать.

Ошибки

Разновидности в семействе ошибок

Перед тем как приручать ошибки, я бы рекомендовал изучить каждый вид и отдельно обратить внимание на самых ярких представителей.

Чтобы ни одна ошибка не ушла незамеченной потребуется включить отслеживание всех ошибок с помощью функции error_reporting(), а с помощью директивы display_errors включить их отображение:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

Фатальные ошибки

Самый грозный вид ошибок — фатальные, они могут возникнуть как при компиляции, так и при работе парсера или PHP-скрипта, выполнение скрипта при этом прерывается.

E_PARSE

Это ошибка появляется, когда вы допускаете грубую ошибку синтаксиса и интерпретатор PHP не понимает, что вы от него хотите, например если не закрыли фигурную или круглую скобочку:

<?php
/**
 * Parse error: syntax error, unexpected end of file
 */
{

Или написали на непонятном языке:

<?php
/**
 * Parse error: syntax error, unexpected '...' (T_STRING)
 */
Тут будет ошибка парсера

Лишние скобочки тоже встречаются, и не так важно круглые либо фигурные:

<?php
/**
 * Parse error: syntax error, unexpected '}'
 */
}

Отмечу один важный момент — код файла, в котором вы допустили parse error не будет выполнен, следовательно, если вы попытаетесь включить отображение ошибок в том же файле, где возникла ошибка парсера то это не сработает:

<?php
// этот код не сработает
error_reporting(E_ALL);
ini_set('display_errors', 1);

// т.к. вот тут
ошибка парсера

E_ERROR

Это ошибка появляется, когда PHP понял что вы хотите, но сделать сие не получилось ввиду ряда причин. Эта ошибка так же прерывает выполнение скрипта, при этом код до появления ошибки сработает:

Не был найден подключаемый файл:

/**
 * Fatal error: require_once(): Failed opening required 'not-exists.php' 
 * (include_path='.:/usr/share/php:/usr/share/pear')
 */
require_once 'not-exists.php';

Было брошено исключение (что это за зверь, расскажу немного погодя), но не было обработано:

/**
 * Fatal error: Uncaught exception 'Exception'
 */
throw new Exception();

При попытке вызвать несуществующий метод класса:

/**
 * Fatal error: Call to undefined method stdClass::notExists()
 */
$stdClass = new stdClass();
$stdClass->notExists();

Отсутствия свободной памяти (больше, чем прописано в директиве memory_limit) или ещё чего-нить подобного:

/**
 * Fatal Error: Allowed Memory Size
 */
$arr = array();

while (true) {
    $arr[] = str_pad(' ', 1024);
}

Очень часто встречается при чтении либо загрузки больших файлов, так что будьте внимательны с вопросом потребляемой памяти

Рекурсивный вызов функции. В данном примере он закончился на 256-ой итерации, ибо так прописано в настройках xdebug (да, данная ошибка может проявиться в таком виде только при включении xdebug расширения):

/**
 * Fatal error: Maximum function nesting level of '256' reached, aborting!
 */
function deep() {
    deep();
}
deep();

Не фатальные

Данный вид не прерывает выполнение скрипта, но именно их обычно находит тестировщик. Именно такие ошибки доставляют больше всего хлопот начинающим разработчикам.

E_WARNING

Частенько встречается, когда подключаешь файл с использованием include, а его не оказывается на сервере или вы ошиблись указывая путь к файлу:

/**
 * Warning: include_once(): Failed opening 'not-exists.php' for inclusion
 */
include_once 'not-exists.php';

Бывает, если используешь неправильный тип аргументов при вызове функций:

/**
 * Warning: join(): Invalid arguments passed
 */
join('string', 'string');

Их очень много, и перечислять все не имеет смысла…

E_NOTICE

Это самые распространенные ошибки, мало того, есть любители отключать вывод ошибок и клепают их целыми днями. Возникают при целом ряде тривиальных ошибок.

Когда обращаются к неопределенной переменной:

/**
 * Notice: Undefined variable: a
 */
echo $a;

Когда обращаются к несуществующему элементу массива:

/**
 * Notice: Undefined index: a
 */
$b = [];
$b['a'];

Когда обращаются к несуществующей константе:

/**
 * Notice: Use of undefined constant UNKNOWN_CONSTANT - assumed 'UNKNOWN_CONSTANT'
 */
echo UNKNOWN_CONSTANT;

Когда не конвертируют типы данных:

/**
 * Notice: Array to string conversion
 */
echo array();

Для избежания подобных ошибок — будьте внимательней, и если вам IDE подсказывает о чём-то — не игнорируйте её:

PHP E_NOTICE in PHPStorm

E_STRICT

Это ошибки, которые научат вас писать код правильно, чтобы не было стыдно, тем более IDE вам эти ошибки сразу показывает. Вот например, если вызвали не статический метод как статику, то код будет работать, но это как-то неправильно, и возможно появление серьёзных ошибок, если в дальнейшем метод класса будет изменён, и появится обращение к $this:

/**
 * Strict standards: Non-static method Strict::test() should not be called statically
 */
class Strict {
    public function test() {
        echo "Test";
    }
}

Strict::test();

Данный тип ошибок актуален для PHP версии 5.6, и практически все их выпилили из
7-ки. Почитать подробней можно в соответствующей RFC. Если кто знает где ещё остались данные ошибки, то напишите в комментариях

E_DEPRECATED

Так PHP будет ругаться, если вы используете устаревшие функции (т.е. те, что помечены как deprecated, и в следующем мажорном релизе их не будет):

/**
 * Deprecated: Function split() is deprecated
 */
// данная функция, удалена из PHP 7.0
// считается устаревшей с PHP 5.3
split(',', 'a,b');

В моём редакторе подобные функции будут зачёркнуты:

PHP E_DEPRECATED in PHPStorm

Пользовательские

Этот вид, которые «разводит» сам разработчик кода, я уже давно их не встречал, и не рекомендую вам ими злоупотреблять:

  • E_USER_ERROR — критическая ошибка
  • E_USER_WARNING — не критическая ошибка
  • E_USER_NOTICE — сообщения которые не являются ошибками

Отдельно стоит отметить E_USER_DEPRECATED — этот вид всё ещё используется очень часто для того, чтобы напомнить программисту, что метод или функция устарели и пора переписать код без использования оной. Для создания этой и подобных ошибок используется функция trigger_error():

/**
 * @deprecated Deprecated since version 1.2, to be removed in 2.0
 */
function generateToken() {
    trigger_error('Function `generateToken` is deprecated, use class `Token` instead', E_USER_DEPRECATED);
    // ...
    // code ...
    // ...
}

Теперь, когда вы познакомились с большинством видов и типов ошибок, пора озвучить небольшое пояснение по работе директивы display_errors:

  • если display_errors = on, то в случае ошибки браузер получит html c текстом ошибки и кодом 200
  • если же display_errors = off, то для фатальных ошибок код ответа будет 500 и результат не будет возвращён пользователю, для остальных ошибок — код будет работать неправильно, но никому об этом не расскажет

Приручение

Для работы с ошибками в PHP существует 3 функции:

  • set_error_handler() — устанавливает обработчик для ошибок, которые не обрывают работу скрипта (т.е. для не фатальных ошибок)
  • error_get_last() — получает информацию о последней ошибке
  • register_shutdown_function() — регистрирует обработчик который будет запущен при завершении работы скрипта. Данная функция не относится непосредственно к обработчикам ошибок, но зачастую используется именно для этого

Теперь немного подробностей об обработке ошибок с использованием set_error_handler(), в качестве аргументов данная функция принимает имя функции, на которую будет возложена миссия по обработке ошибок и типы ошибок которые будут отслеживаться. Обработчиком ошибок может так же быть методом класса, или анонимной функцией, главное, чтобы он принимал следующий список аргументов:

  • $errno — первый аргумент содержит тип ошибки в виде целого числа
  • $errstr — второй аргумент содержит сообщение об ошибке
  • $errfile — необязательный третий аргумент содержит имя файла, в котором произошла ошибка
  • $errline — необязательный четвертый аргумент содержит номер строки, в которой произошла ошибка
  • $errcontext — необязательный пятый аргумент содержит массив всех переменных, существующих в области видимости, где произошла ошибка

В случае если обработчик вернул true, то ошибка будет считаться обработанной и выполнение скрипта продолжится, иначе — будет вызван стандартный обработчик, который логирует ошибку и в зависимости от её типа продолжит выполнение скрипта или завершит его. Вот пример обработчика:

<?php
// включаем отображение всех ошибок, кроме E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', 1);

// наш обработчик ошибок
function myHandler($level, $message, $file, $line, $context) {
    // в зависимости от типа ошибки формируем заголовок сообщения
    switch ($level) {
        case E_WARNING:
            $type = 'Warning';
            break;
        case E_NOTICE:
            $type = 'Notice';
            break;
        default;
            // это не E_WARNING и не E_NOTICE
            // значит мы прекращаем обработку ошибки
            // далее обработка ложится на сам PHP
            return false;
    }
    // выводим текст ошибки
    echo "<h2>$type: $message</h2>";
    echo "<p><strong>File</strong>: $file:$line</p>";
    echo "<p><strong>Context</strong>: $". join(', $', 
    array_keys($context))."</p>";
    // сообщаем, что мы обработали ошибку, и дальнейшая обработка не требуется
    return true;
}

// регистрируем наш обработчик, он будет срабатывать на для всех типов ошибок
set_error_handler('myHandler', E_ALL);

У вас не получится назначить более одной функции для обработки ошибок, хотя очень бы хотелось регистрировать для каждого типа ошибок свой обработчик, но нет — пишите один обработчик, и всю логику отображения для каждого типа описывайте уже непосредственно в нём

С обработчиком, который написан выше есть одна существенная проблема — он не ловит фатальные ошибки, и при таких ошибках вместо сайта пользователи увидят лишь пустую страницу, либо, что ещё хуже, сообщение об ошибке. Дабы не допустить подобного сценария следует воспользоваться функцией register_shutdown_function() и с её помощью зарегистрировать функцию, которая всегда будет выполняться по окончанию работы скрипта:

function shutdown() {
    echo 'Этот текст будет всегда отображаться';
}
register_shutdown_function('shutdown');

Данная функция будет срабатывать всегда!

Но вернёмся к ошибкам, для отслеживания появления в коде ошибки воспользуемся функцией error_get_last(), с её помощью можно получить информацию о последней выявленной ошибке, а поскольку фатальные ошибки прерывают выполнение кода, то они всегда будут выполнять роль «последних»:

function shutdown() {
    $error = error_get_last();
    if (
        // если в коде была допущена ошибка
        is_array($error) &&
        // и это одна из фатальных ошибок
        in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])
     ) {
        // очищаем буфер вывода (о нём мы ещё поговорим в последующих статьях)
        while (ob_get_level()) {
            ob_end_clean();
        }
        // выводим описание проблемы
        echo "Сервер находится на техническом обслуживании, зайдите позже";
    }
}
register_shutdown_function('shutdown');

Хотел обратить внимание, что данный код хоть ещё и встречается для обработки ошибок, и вы возможно вы даже с ним столкнётесь, но он потерял актуальность начиная с 7-ой версии PHP. Что пришло на замену я расскажу чуть погодя.

Задание

Дополнить обработчик фатальных ошибок выводом исходного кода файла где была допущена ошибка, а так же добавьте подсветку синтаксиса выводимого кода.

О прожорливости

Проведём простой тест, и выясним — сколько драгоценных ресурсов кушает самая тривиальная ошибка:

/**
 * Этот код не вызывает ошибок
 */

// засекаем время выполнения скрипта
$time= microtime(true);

define('AAA', 'AAA');
$arr = [];
for ($i = 0; $i < 10000; $i++) {
    $arr[AAA] = $i;
}

printf('%f seconds <br/>', microtime(true) - $time);

В результате запуска данного скрипта у меня получился вот такой результат:

0.002867 seconds

Теперь добавим ошибку в цикле:

/**
 * Этот код содержит ошибку
 */

// засекаем время выполнения скрипта
$time= microtime(true);

$arr = [];
for ($i = 0; $i < 10000; $i++) {
    $arr[BBB] = $i; // тут используем константанту, которая у нас не объявлена
}

printf('%f seconds <br/>', microtime(true) - $time);

Результат ожидаемо хуже, и на порядок (даже на два порядка!):

0.263645 seconds

Вывод однозначен — ошибки в коде приводят к лишней прожорливости скриптов — так что во время разработки и тестирования приложения включайте отображение всех ошибок!

Тестирование проводил на различных версиях PHP и везде разница в десятки раз, так что пусть это будет ещё одним поводом для исправления всех ошибок в коде

Где собака зарыта

В PHP есть спец символ «@» — оператор подавления ошибок, его используют дабы не писать обработку ошибок, а положится на корректное поведение PHP в случае чего:

<?php
echo @UNKNOWN_CONSTANT;

При этом обработчик ошибок указанный в set_error_handler() всё равно будет вызван, а факт того, что к ошибке было применено подавление можно отследить вызвав функцию error_reporting() внутри обработчика, в этом случае она вернёт 0.

Если вы в такой способ подавляете ошибки, то это уменьшает нагрузку на процессор в сравнении с тем, если вы их просто скрываете (см. сравнительный тест выше), но в любом случае, подавление ошибок это зло

Задание

Проверьте, как влияет подавление ошибки с помощью @ на предыдущий пример с циклом.

Исключения

В эру PHP4 не было исключений (exceptions), всё было намного сложнее, и разработчики боролись с ошибками как могли, это было сражение не на жизнь, а на смерть… Окунуться в эту увлекательную историю противостояния можете в статье Исключительный код. Часть 1. Стоит ли её читать сейчас? Не могу дать однозначный ответ, лишь хочу заметить, что это поможет вам понять эволюцию языка, и раскроет всю прелесть исключений.

Исключения — исключительные событие в PHP, в отличии от ошибок не просто констатируют наличие проблемы, а требуют от программиста дополнительных действий по обработке каждого конкретного случая.

К примеру, скрипт должен сохранить какие-то данные в кеш файл, если что-то пошло не так (нет доступа на запись, нет места на диске), генерируется исключение соответствующего типа, а в обработчике исключений принимается решение — сохранить в другое место или сообщить пользователю о проблеме.

Исключение — это объект класса Exception либо одного из многих его наследников, содержит текст ошибки, статус, а также может содержать ссылку на другое исключение которое стало первопричиной данного. Модель исключений в PHP схожа с используемыми в других языках программирования. Исключение можно инициировать (как говорят, «бросить») при помощи оператора throw, и можно перехватить («поймать») оператором catch. Код генерирующий исключение, должен быть окружен блоком try, для того чтобы можно было перехватить исключение. Каждый блок try должен иметь как минимум один соответствующий ему блок catch или finally:

try {
    // код который может выбросить исключение
    if (random_int(0, 1)) {
        throw new Exception("One");
    }
    echo "Zero"
} catch (Exception $e) {
    // код который может обработать исключение
    echo $e->getMessage();
}

В каких случаях стоит применять исключения:

  • если в рамках одного метода/функции происходит несколько операций которые могут завершиться неудачей
  • если используемый вами фреймворк или библиотека декларируют их использование

Для иллюстрации первого сценария возьмём уже озвученный пример функции для записи данных в файл — помешать нам может очень много факторов, а для того, чтобы сообщить выше стоящему коду в чем именно была проблема необходимо создать и выбросить исключение:

$directory = __DIR__ . DIRECTORY_SEPARATOR . 'logs';

// директории может не быть
if (!is_dir($directory)) {
    throw new Exception('Directory `logs` is not exists');
}

// может не быть прав на запись в директорию
if (!is_writable($directory)) {
    throw new Exception('Directory `logs` is not writable');
}

// возможно кто-то уже создал файл, и закрыл к нему доступ
if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
    throw new Exception('System can't create log file');
}

fputs($file, date("[H:i:s]") . " donen");
fclose($file);

Соответственно ловить данные исключения будем примерно так:

try {
    // код который пишет в файл
    // ...
} catch (Exception $e) {
    // выводим текст ошибки
    echo "Не получилось: ". $e->getMessage();
}

В данном примере приведен очень простой сценарий обработки исключений, когда у нас любая исключительная ситуация обрабатывается на один манер. Но зачастую, различные исключения требуют различного подхода к обработке, и тогда следует использовать коды исключений и задать иерархию исключений в приложении:

// исключения файловой системы
class FileSystemException extends Exception {}

// исключения связанные с директориями
class DirectoryException extends FileSystemException {
    // коды исключений
    const DIRECTORY_NOT_EXISTS =  1;
    const DIRECTORY_NOT_WRITABLE = 2;
}

// исключения связанные с файлами
class FileException extends FileSystemException {}

Теперь, если использовать эти исключения то можно получить следующий код:

try {
    // код который пишет в файл
    if (!is_dir($directory)) {
        throw new DirectoryException('Directory `logs` is not exists', DirectoryException::DIRECTORY_NOT_EXISTS);
    }

    if (!is_writable($directory)) {
        throw new DirectoryException('Directory `logs` is not writable', DirectoryException::DIRECTORY_NOT_WRITABLE);
    }

    if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
        throw new FileException('System can't open log file');
    }

    fputs($file, date("[H:i:s]") . " donen");
    fclose($file);
} catch (DirectoryException $e) {
    echo "С директорией возникла проблема: ". $e->getMessage();
} catch (FileException $e) {
    echo "С файлом возникла проблема: ". $e->getMessage();
} catch (FileSystemException $e) {
    echo "Ошибка файловой системы: ". $e->getMessage();
} catch (Exception $e) {
    echo "Ошибка сервера: ". $e->getMessage();
}

Важно помнить, что Exception — это прежде всего исключительное событие, иными словами исключение из правил. Не нужно использовать их для обработки очевидных ошибок, к примеру, для валидации введённых пользователем данных (хотя тут не всё так однозначно). При этом обработчик исключений должен быть написан в том месте, где он будет способен его обработать. К примеру, обработчик для исключений вызванных недоступностью файла для записи должен быть в методе, который отвечает за выбор файла или методе его вызывающем, для того что бы он имел возможность выбрать другой файл или другую директорию.

Так, а что будет если не поймать исключение? Вы получите «Fatal Error: Uncaught exception …». Неприятно.

Чтобы избежать подобной ситуации следует использовать функцию set_exception_handler() и установить обработчик для исключений, которые брошены вне блока try-catch и не были обработаны. После вызова такого обработчика выполнение скрипта будет остановлено:

// в качестве обработчика событий
// будем использовать анонимную функцию
set_exception_handler(function($exception) {
    /** @var Exception $exception */
    echo $exception->getMessage(), "<br/>n";
    echo $exception->getFile(), ':', $exception->getLine(), "<br/>n";
    echo $exception->getTraceAsString(), "<br/>n";
});

Ещё расскажу про конструкцию с использованием блока finally — этот блок будет выполнен вне зависимости от того, было выброшено исключение или нет:

try {
    // код который может выбросить исключение
} catch (Exception $e) {
    // код который может обработать исключение
    // если конечно оно появится
} finally {
    // код, который будет выполнен при любом раскладе
}

Для понимания того, что это нам даёт приведу следующий пример использования блока finally:

try {
    // где-то глубоко внутри кода
    // соединение с базой данных
    $handler = mysqli_connect('localhost', 'root', '', 'test');

    try {
        // при работе с БД возникла исключительная ситуация
        // ...
        throw new Exception('DB error');
    } catch (Exception $e) {
        // исключение поймали, обработали на своём уровне
        // и должны его пробросить вверх, для дальнейшей обработки
        throw new Exception('Catch exception', 0, $e);
    } finally {
        // но, соединение с БД необходимо закрыть
        // будем делать это в блоке finally
        mysqli_close($handler);
    }

    // этот код не будет выполнен, если произойдёт исключение в коде выше
    echo "Ok";
} catch (Exception $e) {
    // ловим исключение, и выводим текст
    echo $e->getMessage();
    echo "<br/>";
    // выводим информацию о первоначальном исключении
    echo $e->getPrevious()->getMessage();
}

Т.е. запомните — блок finally будет выполнен даже в том случае, если вы в блоке catch пробрасываете исключение выше (собственно именно так он и задумывался).

Для вводной статьи информации в самый раз, кто жаждет ещё подробностей, то вы их найдёте в статье Исключительный код 😉

Задание

Написать свой обработчик исключений, с выводом текста файла где произошла ошибка, и всё это с подсветкой синтаксиса, так же не забудьте вывести trace в читаемом виде. Для ориентира — посмотрите как это круто выглядит у whoops.

PHP7 — всё не так, как было раньше

Так, вот вы сейчас всю информацию выше усвоили и теперь я буду грузить вас нововведениями в PHP7, т.е. я буду рассказывать о том, с чем вы будете сталкиваться работая над современным PHP проектом. Ранее я вам рассказывал и показывал на примерах какой костыль нужно соорудить, чтобы отлавливать критические ошибки, так вот — в PHP7 это решили исправить, но? как обычно? завязались на обратную совместимость кода, и получили хоть и универсальное решение, но оно далеко от идеала. А теперь по пунктам об изменениях:

  1. при возникновении фатальных ошибок типа E_ERROR или фатальных ошибок с возможностью обработки E_RECOVERABLE_ERROR PHP выбрасывает исключение
  2. эти исключения не наследуют класс Exception (помните я говорил об обратной совместимости, это всё ради неё)
  3. эти исключения наследуют класс Error
  4. оба класса Exception и Error реализуют интерфейс Throwable
  5. вы не можете реализовать интерфейс Throwable в своём коде

Интерфейс Throwable практически полностью повторяет нам Exception:

interface Throwable
{
    public function getMessage(): string;
    public function getCode(): int;
    public function getFile(): string;
    public function getLine(): int;
    public function getTrace(): array;
    public function getTraceAsString(): string;
    public function getPrevious(): Throwable;
    public function __toString(): string;
}

Сложно? Теперь на примерах, возьмём те, что были выше и слегка модернизируем:

try {
    // файл, который вызывает ошибку парсера
    include 'e_parse_include.php';
} catch (Error $e) {
    var_dump($e);
}

В результате ошибку поймаем и выведем:

object(ParseError)#1 (7) {
    ["message":protected] => string(48) "syntax error, unexpected 'будет' (T_STRING)"
    ["string":"Error":private] => string(0) ""
    ["code":protected] => int(0)
    ["file":protected] => string(49) "/www/education/error/e_parse_include.php"
    ["line":protected] => int(4)
    ["trace":"Error":private] => array(0) { }
    ["previous":"Error":private] => NULL
}

Как видите — поймали исключение ParseError, которое является наследником исключения Error, который реализует интерфейс Throwable, в доме который построил Джек. Ещё есть множество других исключений, но не буду мучать — для наглядности приведу иерархию исключений:

interface Throwable
|- Exception implements Throwable
|   |- ErrorException extends Exception
|   |- ... extends Exception
|   `- ... extends Exception
`- Error implements Throwable
    |- TypeError extends Error
    |- ParseError extends Error
    |- ArithmeticError extends Error
    |  `- DivisionByZeroError extends ArithmeticError
    `- AssertionError extends Error

И чуть-чуть деталей:

TypeError — для ошибок, когда тип аргументов функции не совпадает с передаваемым типом:

try {
    (function(int $one, int $two) {
        return;
    })('one', 'two');
} catch (TypeError $e) {
    echo $e->getMessage();
}

ArithmeticError — могут возникнуть при математических операциях, к примеру когда результат вычисления превышает лимит выделенный для целого числа:

try {
    1 << -1;
} catch (ArithmeticError $e) {
    echo $e->getMessage();
}

DivisionByZeroError — ошибка деления на ноль:

try {
    1 / 0;
} catch (ArithmeticError $e) {
    echo $e->getMessage();
}

AssertionError — редкий зверь, появляется когда условие заданное в assert() не выполняется:

ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);

try {
    assert(1 === 0);
} catch (AssertionError $e) {
    echo $e->getMessage();
}

При настройках production-серверов, директивы zend.assertions и assert.exception отключают, и это правильно

Полный список предопределённых исключений вы найдёте в официальном мануале, там же иерархия SPL исключений.

Задание

Написать универсальный обработчик ошибок для PHP7, который будет отлавливать все возможные исключения.

При написании данного раздела были использованы материалы из статьи Throwable Exceptions and Errors in PHP 7.

Единообразие

— Там ошибки, тут исключения, а можно это всё как-то до кучи сгрести?

Да запросто, у нас же есть set_error_handler() и никто нам не запретит внутри оного обработчика бросить исключение:

// Бросаем исключение вместо ошибок
function errorHandler($severity, $message, $file = null, $line = null)
{
    // Кроме случаев, когда мы подавляем ошибки с помощью @
    if (error_reporting() === 0) {
        return false;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
}

// Будем обрабатывать все-все ошибки
set_error_handler('errorHandler', E_ALL);

Но данный подход с PHP7 избыточен, со всем теперь справляется Throwable:

try {
    /** ... **/
} catch (Throwable $e) {
    // отображение любых ошибок и исключений
    echo $e->getMessage();
}

Отладка

Иногда, для отладки кода, нужно отследить что происходило с переменной или объектом на определённом этапе, для этих целей есть функция debug_backtrace() и debug_print_backtrace() которые вернут историю вызовов функций/методов в обратном порядке:

<?php
function example() {
    echo '<pre>';
    debug_print_backtrace();
    echo '</pre>';
}

class ExampleClass {
    public static function method () {
        example();
    }
}

ExampleClass::method();

В результате выполнения функции debug_print_backtrace() будет выведен список вызовов приведших нас к данной точке:

#0  example() called at [/www/education/error/backtrace.php:10]
#1  ExampleClass::method() called at [/www/education/error/backtrace.php:14]

Проверить код на наличие синтаксических ошибок можно с помощью функции php_check_syntax() или же команды php -l [путь к файлу], но я не встречал использования оных.

Assert

Отдельно хочу рассказать о таком экзотическом звере как assert() в PHP. Собственно, этот кусочек можно рассматривать как мимикрию под контрактную методологию программирования, и дальше я расскажу вам как я никогда его не использовал 🙂

Функция assert() поменяла своё поведение при переходе от версии 5.6 к 7.0, и ещё сильней всё поменялось в версии 7.2, так что внимательней читайте changelog’и PHP 😉

Первый случай — это когда вам надо написать TODO прямо в коде, да так, чтобы точно не забыть реализовать заданный функционал:

// включаем asserts в php.ini
// zend.assertions=1
assert(false, "Remove it!");

В результате выполнения данного кода получим E_WARNING:

Warning: assert(): Remove it! failed

PHP7 можно переключить в режим exception, и вместо ошибки будет всегда появляться исключение AssertionError:

// переключаем в режим «исключений»
ini_set('assert.exception', 1);

assert(false, "Remove it!");

В результате ожидаемо получаем исключение AssertionError.

При необходимости, можно выбрасывать произвольное исключение:

assert(false, new Exception("Remove it!"));

Я бы рекомендовал использовать метки @TODO, современные IDE отлично с ними работают, и вам не нужно будет прикладывать дополнительные усилия и ресурсы для работы с ними, хотя с ними велик соблазн «забить»

Второй вариант использования — это создание некоего подобия TDD, но помните — это лишь подобие. Хотя, если сильно постараться, то можно получить забавный результат, который поможет в тестировании вашего кода:

// callback-функция для вывода информации в браузер
function backlog($script, $line, $code, $message) {
    echo $message;
}

// устанавливаем callback-функцию
assert_options(ASSERT_CALLBACK, 'backlog');

// отключаем вывод предупреждений
assert_options(ASSERT_WARNING,  false);

// пишем проверку и её описание
assert(sqr(4) === 16, 'When I send integer, function should return square of it');

// функция, которую проверяем
function sqr($a) {
    return; // она не работает
}

Третий вариант — некое подобие на контрактное программирование, когда вы описали правила использования своей библиотеки, но хотите точно убедится, что вас поняли правильно, и в случае чего сразу указать разработчику на ошибку (я вот даже не уверен, что правильно его понимаю, но пример кода вполне рабочий):

/**
 * Настройки соединения должны передаваться в следующем виде
 *
 *     [
 *         'host' => 'localhost',
 *         'port' => 3306,
 *         'name' => 'dbname',
 *         'user' => 'root',
 *         'pass' => ''
 *     ]
 *
 * @param $settings
 */
function setupDb ($settings) {
    // проверяем настройки
    assert(isset($settings['host']), 'Db `host` is required');
    assert(isset($settings['port']) && is_int($settings['port']), 'Db `port` is required, should be integer');
    assert(isset($settings['name']), 'Db `name` is required, should be integer');

    // соединяем с БД
    // ...
}

setupDb(['host' => 'localhost']);

Если вас заинтересовали контракты, то специально для вас у меня есть ссылочка на фреймворк PhpDeal.

Никогда не используйте assert() для проверки входных параметров, ведь фактически assert() интерпретирует первый параметр (ведёт себя как eval()), а это чревато PHP-инъекцией. И да, это правильное поведение, ведь если отключить assert’ы, то все передаваемые аргументы будут проигнорированы, а если делать как в примере выше, то код будет выполняться, а внутрь отключенного assert’a будет передан булевый результат выполнения. А, и это поменяли в PHP 7.2 🙂

Если у вас есть живой опыт использования assert() — поделитесь со мной, буду благодарен. И да, вот вам ещё занимательно чтива по этой теме — PHP Assertions, с таким же вопросом в конце 🙂

В заключение

Я за вас напишу выводы из данной статьи:

  • Ошибкам бой — их не должно быть в вашем коде
  • Используйте исключения — работу с ними нужно правильно организовать и будет счастье
  • Assert — узнали о них, и хорошо

P.S.

Это репост из серии статей «PHP для начинающих»:

  • Сессия
  • Подключение файлов
  • Обработка ошибок

Если у вас есть замечания по материалу статьи, или возможно по форме, то описывайте в комментариях суть, и мы сделаем данный материал ещё лучше.

Спасибо Максиму Слесаренко за помощь в написании статьи.

Если программа на PHP написана синтаксически некорректно, то интерпретатор выводит на экран соответствующее сообщение, а также указание на файл и строчку в нём, где по его мнению произошла ошибка. Синтаксическая ошибка возникает в том случае, когда код был записан с нарушением грамматических правил. В человеческих языках грамматика важна, но текст с ошибками чаще всего можно понять и прочитать. В программировании всё строго. Любое мельчайшее нарушение — и программа даже не запустится. Примером может быть забытая ;, неправильно расставленные скобки и другие детали.

Вот пример кода с синтаксической ошибкой:

<?php

print_r('Hodor')

Если запустить код выше, то мы увидим следующее сообщение: $ PHP Parse error: syntax error, unexpected end of file in /private/var/tmp/index.php on line 4. Подобные синтаксические ошибки в PHP относятся к разряду «Parse error». Как видно, в конце приводится путь до файла и номер строчки.

С одной стороны, ошибки «Parse error» — самые простые, потому что они связаны исключительно с грамматическими правилами написания кода, а не с самим смыслом кода. Их легко исправить: нужно лишь найти нарушение в записи.

С другой стороны, интерпретатор не всегда может чётко указать на это нарушение. Поэтому бывает, что забытую скобку нужно поставить не туда, куда указывает сообщение об ошибке.

Задание

Это задание не связано с уроком напрямую. Но будет полезным потренироваться с выводом на экран.

Выведите на экран What Is Dead May Never Die.

Упражнение не проходит проверку — что делать? 😶

Если вы зашли в тупик, то самое время задать вопрос в «Обсуждениях». Как правильно задать вопрос:

  • Обязательно приложите вывод тестов, без него практически невозможно понять что не так, даже если вы покажете свой код. Программисты плохо исполняют код в голове, но по полученной ошибке почти всегда понятно, куда смотреть.

В моей среде код работает, а здесь нет 🤨

Тесты устроены таким образом, что они проверяют решение разными способами и на разных данных. Часто решение работает с одними входными данными, но не работает с другими. Чтобы разобраться с этим моментом, изучите вкладку «Тесты» и внимательно посмотрите на вывод ошибок, в котором есть подсказки.

Мой код отличается от решения учителя 🤔

Это нормально 🙆, в программировании одну задачу можно выполнить множеством способов. Если ваш код прошел проверку, то он соответствует условиям задачи.

В редких случаях бывает, что решение подогнано под тесты, но это видно сразу.

Прочитал урок — ничего не понятно 🙄

Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в «Обсуждениях». Идеально, если вы сформулируете непонятные моменты в виде вопросов. Обычно нам нужно несколько дней для внесения правок.

Кстати, вы тоже можете участвовать в улучшении курсов: внизу есть ссылка на исходный код уроков, который можно править прямо из браузера.

Определения

  • Синтаксическая ошибка — нарушение грамматических правил языка программирования.

  • Parse error (ошибка парсинга) — тип ошибок в PHP, возникающих при наличии синтаксических ошибок в коде.

Нашли ошибку? Есть что добавить? Пулреквесты приветствуются https://github.com/hexlet-basics

Действие происходит в CMS WordPress.

Хотел убрать верхнюю панель администратора через файл functions.php. В результате словил эрор
«Parse error: syntax error, unexpected ‘[‘ in /home/p242257/www/newbud.lg.ua/wp-content/themes/neblog/functions.php on line 44».

Что ни делал, убрать не могу. Надеюсь на Ваше понимание и помощь)
Вот исходный код:

if ( ! isset( $content_width ) )
	$content_width = 730;


if ( ! function_exists( 'gpr_styles' ) ) {
	
	function gpr_styles() {
		wp_enqueue_style( 'style', get_stylesheet_uri(), array(), '1.0.0', false  );
		
	}
}
add_action( 'wp_enqueue_scripts', 'gpr_styles' );


//подключаем скрипты

if ( ! function_exists( 'gpr_js' ) ) {

function gpr_js() {
wp_enqueue_script( 'superfish', get_template_directory_uri() . '/scripts/superfish.js',  array('jquery'), '3.1.4', false);
wp_enqueue_script( 'mobilemenu', get_template_directory_uri() . '/scripts/jquery.mobilemenu.js',  array('jquery'), '1.0.0', false);
wp_enqueue_script( 'scroll', get_template_directory_uri() . '/scripts/jquery.scrollTo.js',  array('jquery'), '1.4.2', false);
wp_enqueue_script( 'tips', get_template_directory_uri() . '/scripts/tips.js',  array('jquery'), '1.0.0a', false);
wp_enqueue_script( 'custom', get_template_directory_uri() . '/scripts/custom.js',  array('jquery'), '1.0.0', false);		

	}
}
add_action( 'wp_enqueue_scripts', 'gpr_js' );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) )
		wp_enqueue_script( 'comment-reply' );

	
 // подключаем фид
add_theme_support( 'automatic-feed-links' );
//убираем мусор из шапки	
function removeHeadLinks() {
  remove_action('wp_head', 'rsd_link');
  remove_action('wp_head', 'wlwmanifest_link');
}

add_action('init', 'removeHeadLinks');
remove_action('wp_head', 'wp_generator');
	
 //подключаем смену фона из админки
add_theme_support( 'custom-background' );


//подключаем миниатюры	
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 200, 200, true );
add_image_size('thumbnail', 150, 150, true);       // Thumbnail (default 150px x 150px max)
add_image_size('medium', 300, 300, true);          // Medium resolution (default 300px x 300px max)
add_image_size('large', 640, 640, true);           // Large resolution (default 640px x 640px max)
add_image_size( 'gallery', 400, 400, true ); //(cropped)
   
//подключаем меню   
   function register_main_menus() {
	register_nav_menus(
		array(
      'primary-menu' => 'Меню в шапке',

		)
	);
}
if (function_exists('register_nav_menus')) add_action( 'init', 'register_main_menus' );



//подключаем сайдбары
if ( function_exists('register_sidebar') )
        register_sidebar(array(	
     'name' => 'Главная - левый сайдбар',
            'before_title' => '<div class=" side-title">',
        'after_title' => '</div>',
		'before_widget' => '<div class="side-blok">',
        'after_widget' => '</div><div class="clear"></div>',
    ));

      if ( function_exists('register_sidebar') )
        register_sidebar(array( 
     'name' => 'Главная - правый сайдбар',
            'before_title' => '<div class=" side-title">',
        'after_title' => '</div>',
    'before_widget' => '<div class="side-blok">',
        'after_widget' => '</div><div class="clear"></div>',
    ));
    
    
            if ( function_exists('register_sidebar') )
        register_sidebar(array( 
     'name' => 'Главная - центральный сайдбар',
            'before_title' => '<div class=" side-title">',
        'after_title' => '</div>',
    'before_widget' => '<div class="side-blok">',
        'after_widget' => '</div><div class="clear"></div>',
    ));

            if ( function_exists('register_sidebar') )
        register_sidebar(array( 
     'name' => 'Внутренний сайдбар',
            'before_title' => '<div class=" side-title">',
        'after_title' => '</div>',
    'before_widget' => '<div class="side-blok">',
        'after_widget' => '</div><div class="clear"></div>',
    ));

Updated on April 5, 2022

Parse Error, Syntax Error Unexpected in WordPress [FIXED]

Parse Error: Syntax Error Unexpected ‘ ‘ in WordPress

Table of Contents [TOC]

  • Parse Error: Syntax Error Unexpected ‘ ‘ in WordPress
    • What are parse error: syntax errors ?
    • What Is A Syntax Error?
    • What Causes the PHP parse/syntax errors in WordPress?
    • How to detect syntax error in wordpress?
    • How To Find Parse Error in WordPress?
  • How To Fix parse error syntax error unexpected ‘ ‘ in wordpress Via FTP?
    •  Steps to Fix Syntax Error in WordPress Via FTP
    • Fix Parse Error by Uploading Fresh Files
    • Tools To Help You Fix The Syntax Error in WordPress
  • How To Avoid Syntax Errors?
    • Enable debugging
    • Disable plugins and themes
    • Like this:
    • Related

Trying something new on your WordPress site? Got any of the following errors like

⚠️ parse error: syntax error, unexpected t_string wordpress,

⚠️ parse error syntax error unexpected end of file in wordpress,

⚠️ parse error: syntax error, unexpected t_function wordpress,

⚠️ parse error syntax error unexpected text t_string wordpress,

⚠️ parse error syntax error unexpected if t_if wordpress,

⚠️ wordpress parse error syntax error unexpected expecting or ‘;’

then don’t freak out. You are not the first one to receive the parse error in WordPress. In this article we will show you how to fix the unexpected syntax error in WordPress. The parse error in WordPress isn’t a common error, and it typically occurs through a mistake made by the user.

Sometimes we install a new plugin in our WordPress and when we activate it we get a syntax error. Sometimes that error appears between the content, but sometimes all the content disappears and we only see the error. Or worse, sometimes not even that. We only have a blank screen.

We are here to tell you that this is completely normal if you have seen the “Syntax Error”⚠️ message because WordPress can sometimes be confusing with annoying syntax errors.

These errors occur if the correct PHP syntax rules are not followed. In this tutorial, we will show you how to fix syntax error in WordPress with simple instructions for beginners.

Let’s see how to understand, debug and fix  a syntax error, or alternatively, at least isolate it:

Some Commonly Asked Questions:

  • How to Fix the Syntax Error in WordPress?
  • How to Fix Parse error: syntax error, unexpected ‘ ‘ WordPress?⚠️
  • How to Fix the Parse Error in WordPress?
  • How to debug and fix WordPress Syntax Errors?

In this post you will also know more about:

  • How do you fix a syntax error?
  • What is parse error syntax error unexpected?
  • What is a parse error in WordPress?
  • How do I fix invalid syntax in Python?
  • What causes a syntax error?
  • What Is syntax error with example?

What are parse error: syntax errors ?

parse error syntax error in WordPress

PHP errors⚠️ can occur when your code is being converted from a series of characters to something that is visible to the visitors of your site.

This error may also happen when an update is made by the developer of a theme or an extension (this is rather rare, but it can happen).

For example, you may have made syntax errors in your code by forgetting parentheses, adding spaces or characters.

These errors occur when the PHP code can’t start or finish being parsed. Obviously, if this is the case, something terribly wrong has happened and it may take more than putting some } there to heal your code.

This could be a copy and paste problem. Maybe the developer did not copy and paste the lines of the code as mentioned in the tutorial.

⚠️ The most probable cause of the error is a missing or a mismatched parenthesis in the PHP code

In WordPress, there are typically 3 main kinds of parse error which may occur to your WordPress site:

⚠️ Syntax error – It occurs because of the semicolons, curly brackets or quotations that were used in the PHP code. Either one of them is missing or the wrong ones were added.

⚠️ Unexpected error – It happens when you include a character such as an opening or closing bracket or other similar characters. This is a parse error which occurs when php is still looking for something and reaches the end of the file without finding it. It could be a quote or bracket which is unclosed, and php is still treating the file contents as a part of the quote.

Php is just telling you it was unexpected

⚠️ Undefined constant error – This is the problem with the character missing in an array while referencing a variable or possible scenarios.

It is extremely important to keep in mind that these three kinds of parsing errors have many different variations depending on the specific mistake in the written PHP code.

Related Issue – Fix WordPress Stuck in Maintenance Mode

What Is A Syntax Error?

Fixing the Syntax Error unexpected in wordpress website

The WordPress syntax error is common among users who add code snippets to their WordPress sites. When this error occurs, you usually see something like in the homepage of the website:

⚠️ Parse error: syntax error, unexpected T_FUNCTION in /home/content/94/4245094/html/wp-content/plugins/my-calendar/my-calendar-styles.php on line 465

Often this error happens because a programming language is not used properly, that is, the rules are not followed and the code is written incorrectly. It can be something as simple as not placing a semicolon, or that a complete file is misspelled. When compiling, it will not be understood and that error will appear. The positive thing about this error is that you will know exactly what it is and we will see how to correct it. In case you run a multi wordpress site and want to find out which user activity lead to this error, it can be found by monitoring user activity in wordpress dashboard.

Parse-Error-in-WordPress_-How-to-Fix-Syntax-Errors-in-WordPress

Syntax errors structure:

“Parse error: syntax error, unexpected character in path/to/php-file.php on line number

Undefined constant errors structure:

“Notice: Use of undefined constant constant string – assumed ‘constant string‘ in path/to/php-file.php on line number

Unexpected errors Example

“Parse error: unexpected character in path/to/php-file.php on line number

Unexpected parse errors may list a string instead of a character.

In each of these examples, number refers to the line number and is going to be replaced with actual numbers such as 23 or 1256, for example, though, not necessarily those exact line numbers.

  • The file indicated in the error message is – where the issue persists
  • The line number gives you a hint as to where to look for the mistake.

The character or constant string names give you an idea of what to look for around the indicated line number. These are what needs fixing or else they’re related to what needs correcting.

Related Read Fix Sorry, This File Type Is Not Permitted For Security Reasons

What Causes the PHP parse/syntax errors in WordPress?

Even a small typo error in the wrong place can cause the operation of your entire WordPress page to stop working. However, the message “Syntax error” is not an insoluble problem.

A syntax error is, as a rule, caused by a small critical error in the syntax of your code. A missing comma or an incorrect parenthesis interrupts the entire script. Have you recently installed a snippet or updated a plugin? If this is the case, then you should check this first.

To resolve WordPress syntax errors, you must rework the part of the code that caused this error. Either you delete it completely or you correct the syntax.

As a beginner, it is not uncommon to be quickly frustrated when a single mistake makes the entire site inaccessible. If you have added the code in your WordPress dashboard via the editor area then it is no longer possible to directly access your WordPress code.

How to detect syntax error in wordpress?

If the error appeared just after you have pasted some block of code, check the latter mainly.

Anyway, in the syntax error message, you will see the damaged file and the line of code that you should review. This is also seen when you activate the debug by defining define (‘WP_DEBUG’, true); in wp-config.php.

  • Check that you do not miss any semicolons. There are codes that at first glance do not seem to have an error, and adding a semicolon at the end, the error message disappears.
  • Check that the quotes are in the proper format, in PHP the double and single quotes are used, make sure they are not italic.
  • Check that there is no missing parenthesis to open or close. You can PHP code syntax for any errors using this handy tool.

To identify the origin or cause of this error, follow the steps below:

  • wp-config.php: Activate debug by defining define (‘WP_DEBUG’, true); Normally it will throw the error on the screen where it will indicate the file, the line and the type of error that was found during the execution.
  • Close each order: Check that you do not lack a ; at the close of each line.
  • Check the quotes: In PHP, single quotes and double quotes are used. Sometimes, when copying and pasting, the format is moved and the quotes appear cursive (curly quotes). Example:  “” instead of “” or ‘’ instead of ”.
  • Check the parentheses: It is very common in instructions with leaving a parenthesis to close or to open. Balanced parentheses require every opening parenthesis to be closed in the reverse order opened.

How To Find Parse Error in WordPress?

The easiest way to open a PHP file is to open it using the default text editor on your computer. The default text editor is based on JavaScript which allows it to run on several platforms and CMS like WordPress and is compatible with most web browsers.

The text editors allow us to write while we see the final result of the text.

And ultimately, the editor generates the content as text, images and other elements in HTML code and shows it to us in a similar way to how it will be on our website.

Popular text editors include

  • Notepad++
  • Sublime Text
  • Atom
  • Brackets
  • TextWrangler

Related Read How To Fix “This Account Has Been Suspended” error in WordPress

How To Fix parse error syntax error unexpected ‘ ‘ in wordpress Via FTP?

How To Fix Parse Error Syntax Error Via FTP

In order to fix the Syntax Error in WordPress you need to edit the code that caused this error.  The only possible way to resolve the syntax error is to directly exchange the faulty code via FTP or access the file you last edited using FTP.

 Steps to Fix Syntax Error in WordPress Via FTP

  • >> After installing the FTP program
  • >> connect it to your website
  • >> go to the theme file that needs editing.

In case you forgot which file you need to edit, just look at the error code. The error will tell you exactly which file and which line you need to edit.

  • >> Remove the code you last added / write the code in correct syntax
  • >> Save the file and upload it back to your server
  • >> Come to your WordPress site and refresh the page, and it will open as before..

How to Fix Parse Error Syntax Errors in WordPress

Fix Parse Error by Uploading Fresh Files

  • If you cannot figure out how to fix your code >> try uploading a fresh version of the file.
  • If your theme is the problem >> download a copy of it (the version you’re using).
  • If you only have the original folder archived and have only updated the theme through the WordPress admin ever since >> download a fresh copy of it from your theme provider.
  • If you do choose the WordPress root and your problem is with wp-includes or wp-admin >> you can safely upload fresh copies of these files to your site.

Tools To Help You Fix The Syntax Error in WordPress

If you have already tried the above steps and still get the syntax error, we recommend that you should try the tools given below:

PHP Storm

It is an IDE considered quite complete with its paid version of monthly or annual membership (USD $199) you can receive all the updates. Php Storm is part of JetBrains, and they offer the whole package (including PHPStorm) for USD 649 per year.

However, they offer a version for university students, with the prohibition of use for commercial purposes.

Visual Studio Code

It is a code editor with many features for beginners and experts. Visual Studio Code also accepts multiple extensions and customizations.

Related Read How To Fix WordPress Not Sending Email Issue

How To Avoid Syntax Errors?

The ideal is that you learn PHP because knowledge of a language is what helps you to detect errors in your code at a glance.

Avoiding these errors is as easy as fixing them if you’re at least a little familiar with PHP. You can check your code for syntax mistakes automatically by running it through a PHP code validator.

Otherwise, you can always check your codes before applying them to a website or convert them into a plugin. Here are some tools that can help you:

  • PHP Code Checker
  • W3 Markup Validation Service
  • PHP code Syntax Check 

Here are some tips of the most common syntax mistakes to look out for right off the bat:

  • Make sure there’s only one opening (<?php) and closing tag (?>)per document
  • Add code shouldn’t be inserted in between a function
    • Check for functions that are broken up by other ones

Enable debugging

If you still have the error of the syntax error or the admin area does not work (or you have found the cause but you still want to dig more), you can enable debugging which will show you all the errors.

The problem is that when a fatal error occurs, the script stops executing. If this happens before any content is displayed, you will only see an empty white screen.

To enable debugging, you will need to open the wp-config.php file from your WordPress installation. Find the following line:

define(‘WP_DEBUG’, false);

Replace false with true and reload your site. If this line does not exist, add it at the top.

wordpress_debug_options_wp-config

Instead of the blank page, you will now have a blank page with error messages. It’s not much, but now you can start. If you have not disabled plugins and themes yet, you will be able to determine the source of the problem by viewing the error message.

It should indicate the file in which the error occurred. It could be something like this:

Cannot redeclare get_posts()in/var/www/html/wordpress/wp-content/plugins/my-test-plug my-test-plugin.php on line 38

At the end of the message, you can see that the problem is in line 38, and it’s a plugin called “my-test-plugin”. By disabling this plugin, the site should work.

You can correct this line if you like to change the codes. If it is a plugin from the repository, it would be better to write to the author instead of doing it yourself. By modifying the plugin, you will have to maintain all your modifications, which is a puzzle. It is best to wait for the developer to do it.

If you do not see any error after enabling debugging, try contacting your web host because it may be that debugging is not properly configured on your server.

Disable plugins and themes

Check if the error started when you activated a new theme or plugin, so you should replace it or contact the developer. Often this error does not allow you to log into WordPress, so you must use FTP to remove the plugin or theme.

Disabling all your plugins is one of the easiest and most common ways to solve the wordpress syntax error. A bad update of a plugin is often the cause. If you still have access to your admin area, you can quickly get there by going to “Plugins” to select “Deactivate” from the action menu.

This will disable all your plugins. If that solves the problem, all you have to do is find out which plugin is the culprit. Start activating them one by one while loading the site after each activation.

We hope this article helped you fix parse error syntax error wordpress. Now you know how to fix parse errors, what causes them, and how to avoid them in the future.


Read More About Other Common WordPress Errors:

  • How to Fix Error Establishing a Database Connection in WordPress?
  • Remove “This Site May Be Hacked” From WordPress in Google
  • How to fix “The link you followed has expired” in WordPress?
  • How to Fix Pluggable.php File Errors in WordPress?
  • How To Fix WordPress Upload Failed To Write File To Disk Error?
  • WordPress HTTP Image Upload Error – How To Fix It?

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Synology проверка сетевой среды ошибка
  • Synology проверка диска на наличие ошибок