Php ошибка parse error syntax error unexpected

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 identifiers. It can’t guess your coding intentions.

Function definition syntax abstract

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.

  • Use an IDE or editor for PHP with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    Expected: semicolon

  • 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 T_STRING, expecting ; 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 T_STRING explains which symbol the parser/tokenizer couldn’t process finally. This isn’t necessarily the cause of the syntax mistake, however.

It’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 ; semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

    • If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that.

  • Look at the syntax colorization!

    • Strings and variables and constants should all have different colors.

    • Operators +-*/. 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 " or ' string marker.

    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it’s not ++, --, or parentheses following an operator. Two strings/identifiers 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 if statements into distinct or nested if conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)

    • Add newlines between:

      1. The code you can easily identify as correct,
      2. The parts you’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’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’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 ? : condition operator can compact code and is useful indeed. But it doesn’t aid readability in all cases. Prefer plain if statements while unversed.

    • PHP’s alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons ; for terminating statements/lines.

    • Mismatched string quotes for " or ' 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’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’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, if you can’t fix it.

    • Adopt a source code versioning system. You can always view a diff 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 different editor/viewer on your source. Some problems cannot be found just from looking at your code.

    • Try grep --color -P -n "[x80-xFF]" file.php as the first measure to find non-ASCII symbols.

    • 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  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

    • <?php phpinfo(); for the one invoked through the webserver.

    Those aren’t necessarily the same. In particular when working with frameworks, you will them to match up.

  • Don’t use PHP’s reserved keywords as identifiers 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’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.

Further guides:

  • PHP Debugging Basics by David Sklar
  • Fixing PHP Errors by Jason McCreary
  • PHP Errors – 10 Common Mistakes by Mario Lurig
  • Common PHP Errors and Solutions
  • How to Troubleshoot and Fix your WordPress Website
  • A Guide To PHP Error Messages For Designers — Smashing Magazine

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

In your php.ini generally, or via .htaccess for mod_php,
or even .user.ini with FastCGI setups.

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

<?php
   error_reporting(E_ALL);
   ini_set("display_errors", 1);
   include("./broken-script.php");

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP’s error_log and look into your webserver’s error.log when a script crashes with HTTP 500 responses.

Unexpected ‘?’

Если вы пытаетесь использовать тег <?php внутри другого такого же тега <?php*

$var = 'hello '<?php echo 'world'; ?>;

* Для PHP версий 4.3.1, 4.3.5 — 4.3.11, 4.4.0 — 4.4.1, 5.0.0 — 5.0.5, 4.4.2 — 4.4.9, 5.1.0 — 5.1.6, 5.2.0 — 5.2.17, 5.3.0 — 5.3.29, 5.4.0 — 5.4.45, 5.5.0 — 5.5.38, 5.6.0 — 5.6.40, 7.0.0 — 7.0.33, 7.1.0 — 7.1.33, 7.2.0 — 7.2.34, 7.3.0 — 7.3.31, 7.4.0 — 7.4.24


Если используется оператор null coalescing operator ?? в версиях PHP ниже, чем PHP 7

<?= $a ?? 2; // Работает в PHP 7+
<?= (!empty($a)) ? $a : 2; // Работает во всех версиях PHP

Unexpected ‘?’, expecting variable

Аналогичная ошибка может возникнуть для типов, допускающих значение NULL, например:

function add(?int $sum): ?int {

Что снова указывает на то, что используется устаревшая версия PHP (то же касается CLI). Проверьте версию PHP через phpinfo();. Необходимо будет либо повысить версию, либо переписать код под старые версии, без использования нового синтаксиса



Unexpected ‘continue’ (T_CONTINUE)

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

Unexpected ‘break’ (T_BREAK)

То же самое касаестся break;. Нельзя использовать в выражениях (те, что могут вернуть значение). Используется внутри for, foreach, while, do-while или switch.

Unexpected ‘return’ (T_RETURN)

Если на предыдущих строках произошла синтакцическая ошибка, то при приходе к слову return будет подобная ошибка. Например:

is ($value == null) { // Ожидалось что будет if    
    return $this->unban();
}

или

mysql_query("INSERT INTO 'users' VALUES ('', '$email', '$name', '".md5 ($password)."')" 
                                                                                       ^^^ нет знаков  );
return mysql_insert_id();   

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



Unexpected ‘=’

Может быть вызвано наличием недопустимых символов в имени переменной. Имена переменных должны соответствовать следующим правилам:

Имена переменных соответствуют тем же правилам, что и остальные наименования в PHP. Правильное имя переменной должно начинаться с буквы или символа подчёркивания и состоять из букв, цифр и символов подчёркивания в любом количестве. Это можно отобразить регулярным выражением: ^[a-zA-Z_x80-xff][a-zA-Z0-9_x80-xff]*$

Замечание: Под буквами здесь подразумеваются символы a-z, A-Z и байты от 128 до 255 (0x80-0xff).



Unexpected T_PAAMAYIM_NEKUDOTAYIM

T_PAAMAYIM_NEKUDOTAYIM — это наименование для двойного двоеточия :: на иврите ¯_(ツ)_/¯

Происходит использование двойного двоеточия, вместо стрелочки объекта (статический вызов, вместо вызова метода в нестатическом контексте).

Например в коде указано $cnf::getConfig($key);, а должно быть $cnf->getConfig($key);

Это было возможно в ранних версиях. Возможно ошибка появилась после переноса куда-либо (например нахостинг). Поэтому проверьте версию PHP и либо установится такую же версию, на которой было разработано приложение, либо измените вызов свойства/метода на вызов их не в статическом виде



Unexpected T_OBJECT_OPERATOR

  1. В очень старых версиях PHP (4) нельзя делать «method chaining», т.е. консрукция ниже не сработает

    $item->get_enclosure()->get_link()
    
  2. В версиях ниже *PHP 5.4* нельзя вызвать метод у только что созданного объекта

    $purchaseOrder = (new PurchaseOrderFactory)->instance();
    

    можно вначале создать объект, а только потом вызвать у него метод:

    $purchaseFactory = new PurchaseOrderFactory;
    $purchaseOrder = $purchaseFactory->instance();  
    

    Также нужно обратить внимание на круглые скобки, писать new PurchaseOrderFactory->instance(); нельзя, это невалидно!

  3. Пропущен знак доллара у переменной.

    Например написано mysqli->query, а должно быть $mysqli->query или написано this->transform($lessons) а должно быть $this->transform($lessons)



Unexpected T_DOUBLE_ARROW

Причины:

  1. Использование `=>` при описании массива, но при этом ключевое слово объявления массива было забыто:

    $statement->execute( ':login'=>$_POST['email'] );
    

    должно быть

    $statement->execute(array(':login' => $_POST['email']));
    
  2. Пропущена запятая перед объявлением массива

    Route::post('/updateaccount'[
                               ⇑  
        'uses' => 'UserController@postSaveAccount',
        'as' => 'account.save'
    ]);
    

    должно быть

    Route::post('/updateaccount', [  
                                ⇑    
        'uses' => 'UserController@postSaveAccount',
        'as' => 'account.save'
    ]);
    
  3. Пропущена какой-то закрывающий элемент в пересислении массива

    $saveData = array(
        'mid' => $this->_saveAsUserId,        
        'post_name' => slug($thisShow['title'],
                                              ⇑   Пропущена закрывающая скобка функции slug        
        'post_content' => $thisShow['content'],        
    );
    


Unexpected T_BOOLEAN_OR
Unexpected T_BOOLEAN_AND

Возникают, как правило, вследствие несовпадения открывающих и закрывающих круглых скобок. Пример

if(is_file($filechk1) && (is_file($filechk2))) || (is_file($dirchk1) && (is_file($dirchk2))){
                                             ⇑
    ...
}

или

if ($args == !empty && $command != 'reload'){
             ^^^^^^ Невалидно. должно быть `!empty($args)`
}

или

if(isset($_GET['test'] && strcmp($_GET['test'],'test') == 0)
                     ⇑
                     

Решение: проверьте весь код на соответствие скобок друг другу! Если нужно, то выносите сложные конструкции в отдельные переменные, чтобы не путаться и работайте с ними. Пример

if (IS_REGISTRATOR() && (($params.status === 'W' || $params.status === 'D' || $params.status === 'A') && $params.remark && (($params.subres_level == 0 && ($user_info->selected_title->tid == $params.boss || $user_info->selected_title->tid == $doc_signer_tid || !$params.usertid) || $params.subres_level > 0 && $user_info->selected_title->tid == $params.usertid))) { ... }                       

этот код будет читаться легче в таком виде:

$docIsInWorkAcceptOrDraft = ...;
$bossHasSignerPriviledge = ...;
$userCanSign = ...;

if ($docIsInWorkAcceptOrDraft && $bossHasSignerPriviledge && $userCanSign) {
  // ...
}   

Антон Шевчук // 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. Спасибо Максиму Слесаренко за помощь в написании статьи

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?

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?

If you’ve ever updated a plugin or pasted code into your WordPress website, chances are you’ve problem seen the parse error syntax error unexpected end in WordPress message. This is a common error because it only takes one character to cause it. In this article, we’ll explore what causes this error and see how to fix it.

  • 1
    What Does Parse Error: Syntax Error, Unexpected End in WordPress Mean?

  • 2
    How to Solve Parse Error: Syntax Error Unexpected End in WordPress

  • 3
    Testing the Parse Error Syntax Error Unexpected End in WordPress

    • 3.1
      Editing Plugin Code

  • 4
    Fixing the Parse Error When You Can’t Find the Error

    • 4.1
      Debug Mode

    • 4.2
      Debugging Plugin

  • 5
    Fixing the Parse Error if You’re Locked Out of WordPress

  • 6
    Restoring a Previous File

    • 6.1
      Upload a Clean Copy of WordPress

  • 7
    Ending Thoughts on the Parse Error Syntax Error Unexpected End in WordPress

What Does Parse Error: Syntax Error, Unexpected End in WordPress Mean?

Parse error syntax error unexpected end in WordPress can be the simplest of errors and still cause a big problem.

The error has two parts:

Syntax Error – This error is caused by an error in the PHP structure when a character is missing or added that shouldn’t be there.

Unexpected – This means the code is missing a character and PHP reaches the end of the file without finding what it’s looking for. The error will include information at the end that explains what it saw that was unexpected.

If you see Parse Error: Syntax Error, Unexpected end in WordPress, it just means that WordPress detected that something in the code is missing or added. It can be something as simple as a comma, semi-colon, a closing parenthesis, or one too many brackets.

The missing syntax can be within code that you’ve written or pasted into your website, or within a theme or plugin that you’ve installed or updated.

Fortunately, it’s not that difficult to find and fix. However, you will need to understand how code works and how to edit it.

How to Solve Parse Error: Syntax Error Unexpected End in WordPress

How to Solve Parse Error

The actual parse error syntax error unexpected end in WordPress will have a different ending depending on what’s causing the error.

Examples include:

  • 1) syntax error, unexpected end of file
  • 2) syntax error, unexpected token
  • 3) syntax error, unexpected variable
  • 4) syntax error, unexpected identifier

The error message will usually identify the specific token, variable, identifier, etc., that it doesn’t like. We’ll see a few examples of this as we go.

Testing the Parse Error Syntax Error Unexpected End in WordPress

Before testing anything, it is always a good idea to create a staging site or use a backup plugin to create and download a backup of your site (just in case). In fact, if you have a recent backup, you may try to restore that one and see if that gets rid of the error. If not, you’ll still want a backup in case anything else breaks during testing.

WordPress has made lots of improvements in how it handles code. Now, instead of running bad code and killing your website, if it has a previous version of the code that ran, it tries to use that code instead when displaying the site to visitors.

This keeps your site from displaying the error to your visitors and keeps you from being locked out. It is still possible for your site to go down and lock you out, but it’s more difficult now.

Also, the code editors now show markup, so it’s easy to identify variables and other code elements. This makes it easier to test code within the plugin and theme code editors within WordPress.

Unfortunately, WordPress doesn’t always give you a clear message. Sometimes there is no message, content is missing, or it just doesn’t show the website. All of these can be fixed, but they might take a little more troubleshooting.

Let’s look at a few examples. We’ll start with something easy.

Editing Plugin Code

Editing Plugin Code

First, start with what you did last. In this example, I’ve edited code in a plugin file. The file reverted to the last known good code, so my changes are not working. Look at the error. It will tell you what’s causing the error code and the line of code with the error.

In this example, WordPress is seeing an unexpected bracket when it’s expecting to see a semi-colon.

This one is simple. First, look at the line above it. We see the word break, ending case 4. We’re fortunate in that we have other cases to compare to. Above it is case 3, which also ends with break, but this one has a closing semi-colon.

Editing Plugin Code

Next, edit the code that caused the error.

Editing Plugin Code

Here’s another example in the same plugin file. This one is showing the error on line 488. However, that line of code is correct. It’s giving me a clue, though. It’s identifying this as an unexpected variable.

Editing Plugin Code

If we look at the code above 488, we see that it’s missing a closing bracket. This causes WordPress to see the next line incorrectly.

Editing Plugin Code

Simply add the closing bracket and update the file. The code now works correctly.

These problems were simple, but most of the time you see a parse error syntax error unexpected end in WordPress, it’s exactly like these examples.

Fixing the Parse Error When You Can’t Find the Error

There are two ways to find the parse error if it doesn’t display for you or you’re not sure where it’s coming from. Here’s a look at both methods.

Debug Mode

The first step is to enable the WordPress error log. Go to your wp-config file using FTP or cPanel. Search for a line of code that looks like this:

define( 'WP_DEBUG', false );

If you have this code, change false to true.

If you don’t have this line of code, look for a line that says:

“Stop editing! Happy blogging.” and paste this code:

define( 'WP_DEBUG', true );

Load the website. This will display the error and you now have a place to start troubleshooting.

Debugging Plugin

Query Monitor

Query Monitor is one of the most popular debugging plugins. It provides tools that you can access from the frontend and backend from the top menu bar and as an overlay.

Query Monitor

This will enable several debugging tools including an error log where you can find the information you need.

Fixing the Parse Error if You’re Locked Out of WordPress

Fixing the Parse Error if You’re Locked Out of WordPress

If you’re locked out of the admin dashboard, you’ll need to make your changes another way. You’ll need to download the file from the server that contains the error and open it in a code editor to make your edits.

In my case, I was making changes in the functions.php file for the Twenty Twenty One theme. I made an error in my syntax and my site went down. All it shows is this error that doesn’t help.

Fixing the Parse Error if You’re Locked Out of WordPress

The best options are to use FTP or your host’s cPanel. I’ll use cPanel for this example, but the process is the same. First, open File Manager in cPanel.

Fixing the Parse Error if You’re Locked Out of WordPress

Next, open the folder for the website you’re working on. If it’s the primary site, you might see a globe icon. Otherwise, open the folder with the name of the website.

Fixing the Parse Error if You’re Locked Out of WordPress

Navigate to the wp-content folder.

Fixing the Parse Error if You’re Locked Out of WordPress

Navigate to the folder with the theme or plugin you want to edit. In this case, I’m editing a theme.

Fixing the Parse Error if You’re Locked Out of WordPress

Select the folder of the theme or plugin. I’m selecting the folder for the Twenty Twenty One theme.

Fixing the Parse Error if You’re Locked Out of WordPress

Next, go to the file you were editing when the problem occurred. I was editing the functions.php file. Either download the file to work offline or edit the file. I recommend downloading a backup before making changes.

Fixing the Parse Error if You’re Locked Out of WordPress

Your code editor might provide information about the error. In my case, it’s showing that it’s expecting a parenthesis on line 29. In reality, it’s missing a bracket on line 17, which causes the editor to think it needs a parenthesis.

Fixing the Parse Error if You’re Locked Out of WordPress

Adding the bracket removes the error. I can now upload my new file to replace the current file or save it if I’m using the online editor.

Fixing the Parse Error if You’re Locked Out of WordPress

My website now works as normal.

Restoring a Previous File

Restoring a Previous File

If you’re not sure what’s changed in the code and you want to restore a previous file that you know works, go to the file in FTP or cPanel.

Sometimes WordPress doesn’t tell you where the problem is coming from. In this case, you can rename the folders one at a time to see if the problem goes away. Start with your plugins.

If you do know where the problem is coming from, you can upload a replacement file. For a plugin or theme in the WordPress repository, you can delete the folder and reinstall it.

If you prefer, you can download the theme or plugin from the WordPress repository (or where you got it from), unzip the file, and only replace the file you need to. It works similarly to how we’ll replace WordPress in the next section.

Upload a Clean Copy of WordPress

Upload a Clean Copy of WordPress

If the problem is the WordPress core, you can upload a new version of WordPress without deleting your files. Download a new copy of WordPress and unzip it.

Upload a Clean Copy of WordPress

Next, delete the wp-content folder and the file called wp-config-sample.php.

Upload a Clean Copy of WordPress

Next, upload the WordPress files from the unzipped folder into your WordPress root folder. This will overwrite all files except for the two you deleted. Your site should work now.

Ending Thoughts on the Parse Error Syntax Error Unexpected End in WordPress

The parse error syntax error unexpected end in WordPress is a common error for anyone handling code. It’s not difficult to fix, but it can sometimes take time to track it down. The steps are simple:

  • If you’ve added code, start there.
  • If you’ve installed a plugin or theme, deactivate it.
  • When you can’t find the problem, replace the suspected files.
  • When all else fails, restore a backup.

Following a few troubleshooting steps will help get your site running smoothly as fast as possible.

We want to hear from you. Have you had the parse error syntax error unexpected end in WordPress? Let us know how you fixed it in the comments below.

Featured Image via alexdndz / shutterstock.com

When installing the Perfmatters plugin, it’s rare, but you might run into an error like this which prevents you from activating the plugin:

Plugin could not be activated because it triggered a fatal error.
Parse error: syntax error, unexpected '?' in /www/wp-content/plugins/perfmatters/inc/functions.php on line xxxx

The reason for this is usually because you’re using a very old version of PHP. We currently require PHP 7.0 (released in 2015) or higher for Perfmatters to work properly.

How to check your PHP version

Follow the steps below to check what version of PHP you’re running.

Step 1

Under “Tools” in your WordPress dashboard click on “Site Health.”

WordPress Site Health tool

WordPress Site Health tool

Step 2

Click on the “Info” tab.

WordPress site info

WordPress site info

Step 3

Scroll down and expand the “Server” section. You should see the PHP version you’re running.

WordPress PHP version

WordPress PHP version

While we only require PHP 7.0 or higher, WordPress officially recommends PHP 7.4 or higher. Any version below PHP 7.4 is actually a big security risk and bad for performance since it’s no longer updated, developed, or supported.

If you need to update your PHP version, the easiest thing to do is check with your hosting provider or their documentation. Some hosting providers, like Kinsta, even have a toggle where you can easily switch between PHP versions.

Change PHP version

Change PHP version

Действие происходит в 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>',
    ));

Если программа на 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

Понравилась статья? Поделить с друзьями:
  • Php ошибка 500 как вывести
  • Php ошибка 404 не найдено
  • Php ошибка 200 что это
  • Phpmyadmin ошибка конфигурация уже существует настройка отключена
  • Php отобразить ошибки на странице