Parse error syntax error unexpected public

I am getting this error in this PHP code on line 3, what could be wrong? This code has been taken from php manual user notes by frank at interactinet dot com <?php public function myMethod() {

I am getting this error in this PHP code on line 3, what could be wrong? This code has been taken from php manual user notes by frank at interactinet dot com

<?php

public function myMethod()
{
return 'test';
}

public function myOtherMethod()
{
return null;
}

if($val = $this->myMethod())
{
 // $val might be 1 instead of the expected 'test'
}

if( ($val = $this->myMethod()) )
{
// now $val should be 'test'
}

// or to check for false
if( !($val = $this->myMethod()) )
{
// this will not run since $val = 'test' and equates to true
}

// this is an easy way to assign default value only if a value is not returned:

if( !($val = $this->myOtherMethod()) )
{
$val = 'default'
}

?> 

ceejayoz's user avatar

ceejayoz

175k40 gold badges295 silver badges363 bronze badges

asked Nov 12, 2012 at 9:43

Ashish Yadav's user avatar

2

The public keyword is used only when declaring a class method.

Since you’re declaring a simple function and not a class you need to remove public from your code.

RiggsFolly's user avatar

RiggsFolly

92.5k20 gold badges102 silver badges148 bronze badges

answered Nov 12, 2012 at 9:44

DiverseAndRemote.com's user avatar

3

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

answered Nov 12, 2012 at 10:03

Содержание

  1. Ошибка Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file in D:localhtdocsaddlibsDatabase.php on line 31?
  2. PHP для начинающих. Обработка ошибок // PHP
  3. Ошибки
  4. Разновидности в семействе ошибок
  5. Фатальные ошибки
  6. Не фатальные
  7. Обрабатываемые
  8. Приручение
  9. О прожорливости
  10. Где собака зарыта
  11. Исключения
  12. PHP7 – всё не так, как было раньше
  13. Отладка
  14. Assert
  15. В заключение

Ошибка Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file in D:localhtdocsaddlibsDatabase.php on line 31?

host . ‘;dbname=’ . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try <
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
>
// Catch any errors
catch(PDOException $e) <
$this->error = $e->getMessage();
>
>
>

public function query($query) <
$this->stmt = $this->dbh->prepare($query);
>

public function bind($param, $value, $type = null) <
if (is_null($type)) <
switch (true) <
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
>
>
$this->stmt->bindValue($param, $value, $type);
>

public function execute() <
return $this->stmt->execute();
>
public function resultset() <
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
>
public function single() <
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
>
public function rowCount() <
return $this->stmt->rowCount();
>

public function beginTransaction() <
return $this->dbh->beginTransaction();
>

public function endTransaction() <
return $this->dbh->commit();
>

public function cancelTransaction() <
return $this->dbh->rollBack();
>
public function debugDumpParams() <
return $this->stmt->debugDumpParams();
>

Источник

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

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

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

Ошибки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Не фатальные

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Теперь, когда вы познакомились с большинством видов и типов ошибок, пора озвучить небольшое пояснение по работе директивы 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 , то ошибка будет считаться обработанной и выполнение скрипта продолжится, иначе — будет вызван стандартный обработчик, который логирует ошибку и в зависимости от её типа продолжит выполнение скрипта или завершит его. Вот пример обработчика:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Исключения

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Т.е. запомните – блок 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 :

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

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

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

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

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

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

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

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

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

Отладка

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

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

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

Assert

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

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

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

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

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

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

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

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

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

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

В заключение

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

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

Источник

I had a helper class conflict with two of my modules. I have resolved this issue by doing following:

if (Mage::helper('core')->isModuleEnabled('Amasty_Methods')) {
    class Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp extends Amasty_Methods_Helper_Payment_Data {}
}  
else {
    class Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp extends Mage_Payment_Helper_Data {}
}

class Ebizmarts_SagePaySuite_Helper_Payment_Data extends Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp {
}
    /**
     * Retrieve all payment methods
     *
     * @param mixed $store
     * @return array
     */
    public function getPaymentMethods($store = null)
    {
        $_methods = parent::getPaymentMethods($store);

        if (isset($_methods['sagepaysuite'])) {
            unset($_methods['sagepaysuite']);
        }
        return $_methods;
    }
}

Now, I get the error:

Parse error: syntax error, unexpected ‘public’ (T_PUBLIC) in /domains/dev.domain.co.uk/http/app/code/local/Ebizmarts/SagePaySuite/Helper/Payment/Data.php on line 26

Do I just delete the public from my function? Also what are the consequences of doing so?

asked Oct 23, 2017 at 10:11

Greg's user avatar

GregGreg

2,8493 gold badges37 silver badges76 bronze badges

1

There is one } to much … replace

class Ebizmarts_SagePaySuite_Helper_Payment_Data extends Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp {
}

with

class Ebizmarts_SagePaySuite_Helper_Payment_Data extends Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp {

answered Oct 23, 2017 at 10:20

sv3n's user avatar

sv3nsv3n

11.6k7 gold badges37 silver badges69 bronze badges

2

I had the closing curly bracket after class Ebizmarts_SagePaySuite_Helper_Payment_Data extends Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp {
}

Deleting the } solved my issue.

Now, it works fine with the Public declarations in the function.

Sorry to bother you all.

answered Oct 23, 2017 at 10:20

Greg's user avatar

GregGreg

2,8493 gold badges37 silver badges76 bronze badges

4

  1. Home

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

92 votes

6 answers

Get the solution ↓↓↓

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:

  • Unexpected T_STRING

  • Unexpected T_VARIABLE

  • Unexpected T_CONSTANT_ENCAPSED_STRING

  • Unexpected $end

  • Unexpected T_FUNCTION…

  • Unexpected

  • Unexpected

  • Unexpected T_IF

  • Unexpected T_LNUMBER

  • Unexpected ?

  • Unexpected continue (T_CONTINUE)

  • Unexpected ‘=’

  • Unexpected T_INLINE_HTML…

  • Unexpected T_PAAMAYIM_NEKUDOTAYIM…

  • Unexpected T_OBJECT_OPERATOR…

  • Unexpected T_DOUBLE_ARROW…

  • Unexpected T_SL…

  • Unexpected T_BOOLEAN_OR…

    Unexpected T_BOOLEAN_AND…

  • Unexpected T_IS_EQUAL

  • Unexpected T_NS_SEPARATOR…

  • Unexpected character in input: ‘

  • Unexpected ‘public’ (T_PUBLIC) …

  • Unexpected T_STATIC…

  • Unexpected T_CLASS…

  • Unexpected ‘use’ (T_USE)

  • Unexpected T_DNUMBER

  • Unexpected (comma)

  • Unpexected (period)

  • Unexpected (semicolon)

  • Unexpected (asterisk)

  • Unexpected (colon)

  • Unexpected ‘:’, expecting ‘,’ or ‘)’

  • Unexpected (call-time pass-by-reference)

  • Unexpected

Closely related references:

  • What does this error mean in PHP? (runtime errors)
    • Parse error: syntax error, unexpected T_XXX
    • Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
    • Parse error: syntax error, unexpected T_VARIABLE
  • What does this symbol mean in PHP? (language tokens)
  • Those

And:

  • The PHP manual on php.net and its various language tokens
  • Or Wikipedia’s syntax introduction on PHP.
  • And lastly our of course.

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.

2022-06-3

Write your answer


511

votes

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.

{-code-18}-code-7}Function

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 with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    {-code-18}-code-7}Expected:

  • 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 ad{-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.

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

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

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 generally, or via for mod_php,
or even with FastCGI setups.

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, saytest.php:

<{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}?php
   error_reporting(E_ALL){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   ini_set({-code-18}-code-7}display_errors{-code-18}-code-7}, 1){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   include({-code-18}-code-7}./broken-script.php{-code-18}-code-7}){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP{-code-18}-code-8}serror_log and look into your webserver{-code-18}-code-8}s when a script crashes with HTTP 500 responses.


49

votes

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):

  1. NetBeans [free]
  2. PHPStorm [$199 USD]
  3. Eclipse with PHP Plugin [free]
  4. Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)


981

votes

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}.

{-code-17}php53 = array{-code-12}1, 2, 3{-code-23};
{-code-17}php54 = {-code-11}-code-1}1, 2, 3{-code-21};
         ⇑

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

{-code-17}result = get_whatever{-code-12}{-code-23}{-code-11}-code-1}"key"{-code-21};
                      ⇑

Reference — What does this error mean in PHP? — «Syntax error, unexpected shows the most common and practical workarounds.

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.

See also:

  • PHP syntax for dereferencing function result в†’ possible as of PHP 5.4
  • PHP syntax error, unexpected ‘{-code-11}-code-1}’
  • Shorthand for arrays: is there a literal syntax like {-code-11}} or {-code-11}-code-1}{-code-21}?
  • PHP 5.3.10 vs PHP 5.5.3 syntax error unexpected ‘{-code-11}-code-1}’
  • PHP Difference between {-code-11}-code-3} and {-code-11}-code-1}{-code-21}
  • PHP Array Syntax Parse Error Left Square Bracket «{-code-11}-code-1}»

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:

  • You can’t use array property declarations/expressions in classes, not even in PHP 7.

    protected {-code-17}var{-code-11}-code-1}"x"{-code-21} = "Nope";
                  ⇑
    
  • Confusing{-code-11}-code-1} with opening curly braces{-code-11} or parentheses{-code-12} is a common oversight.

    foreach {-code-11}-code-1}{-code-17}a as {-code-17}b{-code-23}
            ⇑
    

    Or even:

    function foobar{-code-11}-code-1}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                   ⇑
    
  • Or trying to dereference {-code-16}ants {-code-12}before PHP 5.6{-code-23} as arrays:

    {-code-17}var = {-code-16}{-code-11}-code-1}123{-code-21};
           ⇑
    

    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:

    {-code-19} {-code-17}var{-code-11}-code-1}'key'{-code-21};
    

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:

    function foobar{-code-12}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                              ⇑
    
  • Or trying to end an array where there isn’t one:

    {-code-17}var = 2{-code-21};
    

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

    {-code-17}array = {-code-11}-code-1}1,{-code-11}-code-1}2,3{-code-21},4,{-code-11}-code-1}5,6{-code-11}-code-1}7,{-code-11}-code-1}8{-code-21},{-code-11}-code-1}9,10{-code-21}{-code-21},11{-code-21},12{-code-21}{-code-21},15{-code-21};
                                                 ⇑
    

    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.


600

votes

Answer

Solution:

Unexpected {-code-1{-code-16}

An «{-code-13{-code-16}unexpected{-code-1{-code-16}«{-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{-code-4{-code-16}

purposefully abstract/inexact operator+{-code-2{-code-16} diagram

  1. 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:

            {-code-3{-code-16}
    
  2. String concatenation

    A frequent mishap are string concatenations with {-code-14{-code-16}gotten{-code-4{-code-16} operator:

                                    {-code-5{-code-16}
    

    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{-code-4{-code-16}

    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{-code-4{-code-16}

  3. Missing expression operators

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

                {-code-7{-code-16}
    

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

  4. Lists

    Same {-code-14{-code-16} syntax {-code-11{-code-16}s{-code-8{-code-16} like in array populations{-code-8{-code-16} where the parser also indicates an expected comma{-code-8{-code-16} {-code-14{-code-16} example:

                                           ⇓
     $var = array{-code-23}"{-code-13{-code-16}1"{-code-13{-code-16} =>{-code-13{-code-16} $val{-code-8{-code-16} $val2{-code-8{-code-16} $val3 $val4){-code-13{-code-16}
    

    Or functions parameter {-code-11{-code-16}s:

                                     ⇓
     function myfunc{-code-23}$param1{-code-8{-code-16} $param2 $param3{-code-8{-code-16} $param4)
    

    Equivalently do you see this with{-code-11{-code-16} or{-code-12{-code-16} statements{-code-8{-code-16} or when lacking a{-code-13{-code-16} semicolon in a{-code-14{-code-16} loop{-code-4{-code-16}

  5. 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:

     class xyz {      ⇓
         var $value = $_GET["{-code-13{-code-16}input"{-code-13{-code-16}]{-code-13{-code-16}
    

    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{-code-4{-code-16}

  6. Variables after ident{-code-19}iers

    You can also never have a variable follow an ident{-code-19}ier directly:

                  ⇓
     $this->{-code-13{-code-16}myFunc$VAR{-code-23}){-code-13{-code-16}
    

    Btw{-code-8{-code-16} this is a common example where the intention was to use variable variables perhaps{-code-4{-code-16} In this case a variable property lookup with$this->{-code-13{-code-16}{"{-code-13{-code-16}myFunc$VAR"{-code-13{-code-16}{-code-16}{-code-23}){-code-13{-code-16} {-code-14{-code-16} example{-code-4{-code-16}

    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{-code-4{-code-16}

  7. 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:

            ⇓
     {-code-14{-code-16}each $array as $key) {
    

    Solution: add the missing opening{-code-23} between statement and variable{-code-4{-code-16}

                           ⇓
     {-code-19} {-code-23}$var = pdo_query{-code-23}$sql) {
          $result = …
    

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

  8. Else does not expect conditions

         ⇓
    else {-code-23}$var >{-code-13{-code-16}= 0)
    

    Solution: Remove the conditions fromelse or use {-code-4{-code-16}

  9. Need brackets {-code-14{-code-16} closure

         ⇓
    function{-code-23}) use $var {{-code-16}
    

    Solution: Add brackets around$var{-code-4{-code-16}

  10. Invisible whitespace

    As mentioned in the reference answer on «{-code-13{-code-16}Invisible stray Unicode»{-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:

    <{-code-13{-code-16}?php
                              в‡ђ
    $var = new PDO{-code-23}{-code-4{-code-16}{-code-4{-code-16}{-code-4{-code-16}){-code-13{-code-16}
    

    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{-code-4{-code-16}

See also

  • Search: unexpected {-code-1{-code-16}


248

votes

Answer

Solution:

Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy namesT_CONSTANT_ENCAPSED_STRING andT_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.

  1. Incorrect variable interpolation

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

                              ⇓     ⇓
    echo "Here comes a $wrong['array'] access";
    

    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:

    echo "This is only $valid[here] ...";
    

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

    echo "Use {$array['as_usual']} with curly 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.

  2. 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:

                           ⇓
    print "Hello " . WORLD  " !";
    

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

  3. 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.

                    ⇓
    print "<a href="' . $link . '">click here</a>";
          вЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџвЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџвЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџ
    

    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:

    print "<a href="{$link}">click here</a>";
    

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

  4. Missing opening quote

    Equivalently are forgotten opening a recipe for parser errors:

                   ⇓
     make_url(login', 'open');
    

    Here the', ' would become a string literal after a bareword, when obviouslylogin was meant to be a string parameter.

  5. Array lists

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

    array(               ⇓
         "key" => "value"
         "next" => "....",
    );
    

    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.

  6. Function parameter lists

    The same thing for function calls:

                             ⇓
    myfunc(123, "text", "and"  "more")
    
  7. Runaway strings

    A common variation are quite simply forgotten string terminators:

                                    ⇓
    mysql_evil("SELECT * FROM stuffs);
    print "'ok'";
          ⇑
    

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

  8. HEREDOC indentation

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

    print <<< HTML
        <link..>
        HTML;
       ⇑
    

    Solution: upgrade PHP or find a better hoster.

See also

  • Interpolation (double quoted string) of Associative Arrays in PHP
  • PHP — syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
  • Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in PHP
  • Unexpected T_CONSTANT_ENCAPSED_STRING error in SQL Query


79

votes

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.

  1. 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:

                   ⇓                  ⇓
     {-code-11} {-code-5}<{-code-29}a href={-code-5}http://example.com{-code-5}>{-code-29}click here<{-code-29}/a>{-code-29}{-code-5}{-code-29}
    

    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:

    {-code-14} = {-code-6}<{-code-29}div>{-code-29}some text with {-code-25}php {-code-11} {-code-6}some php entry{-code-6} ?>{-code-29}<{-code-29}/div>{-code-29}{-code-6}
    

    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

    See also What is the difference between single-quoted and double-quoted strings in PHP?.

  2. Unclosed strings

    If you miss a closing then a syntax error typically materializes later. An unterminated string will often consume a bit of code until the next intended string value:

                                                           ⇓
    {-code-11} {-code-5}Some text{-code-5}, {-code-32}a_variable, {-code-5}and some runaway string {-code-29}
    success({-code-5}finished{-code-5}){-code-29}
             в‡Ї
    

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

  3. 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:

    {-code-14} = ’Something something..’ + {-code-20} ain{-code-6}t quotes”{-code-29}
    

    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.

  4. 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:

           {-code-21}
    

    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.

  5. 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:

          ⇓
    {-code-23} {-code-27}={-code-5}1.0{-code-5}?>{-code-29}
    


Share solution ↓

Additional Information:

Date the issue was resolved:

2022-06-3

Link To Source

Link To Answer
People are also looking for solutions of the problem: a non-numeric value encountered

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

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

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.

Hello,

Following code gives me error

«The website encountered an unexpected error. Please try again later.
ParseError: syntax error, unexpected ‘public’ (T_PUBLIC) in ComposerAutoloadincludeFile() (line 41 of modulescustomrsvplistsrcEnablerService.php).»

<?php
/**
 * @file
 * Contains DrupalrsvplistEnablerService
 */

namespace Drupalrsvplist;

use DrupalCoreDatabaseDatabase;
use DrupalnodeEntityNode;

/**
 * Defines a service for managing RSVP list enabled for nodes. 
 */
class EnablerService {
 /**
 * Constructor
 */
 public function __construct() {

 /**
 * Sets an individual node to be RSVP enabled. 
 *
 * @param DrupalnodeEntityNode $node
 */

 function setEnabled(Node $node) {
   if (!$this->isEnabled($node)){
      $insert = Database::getConnection()->insert('rsvplist_enabled');
      $insert->fields(array('nid'), array($node->id()));
      $insert->execute();
  }
}

  /**
 * checks if an individual node is RSVP enabled. 
 *
 * @param DrupalnodeEntityNode $node
 */

  public function isEnabled(Node $node) {
    if ($node->isNew()) {
      return FALSE;
    }

    $select = Database::getConnection()->select('rsvplist_enabled', 're');
    $select->fields('re', array('nid'));
    $select->condition('nid', $node->id());
    $results = $select->execute();
    return !empty($results->fetchCol());
    }

    /**
* Deletes. 
*
* @param DrupalnodeEntityNode $node
*/
function delEnabled(Node $node) {
  $delete = Database::getConnection()->delete('rsvplist_enabled');
  $delete->condition('nid', $node->id());
  $delete->execute();
}
 }}

If I remove public, then I get this error:
 

Error: Call to undefined method DrupalrsvplistEnablerService::isEnabled() in rsvplist_form_node_form_alter() (line 29 of modulescustomrsvplistrsvplist.module).
 

.module file:

line 29:
 

 '#default_value' => $enabler->isEnabled($node),
function rsvplist_form_node_form_alter(&$form, DrupalCoreFormFormStateInterface $form_state, $form_id) {
	$node = $form_state->getFormObjecT()->getEntity();
	$current_node_type = $node->getType();
	$config = Drupal::Config('rsvplist.settings');
	$types = $config->get('allowed_types', array());
	// rsvp options for admin
	if (in_array($current_node_type, $types)){
	$form['rsvplist'] = array(
	 '#type' => 'details',
	 '#title' => t('RSVP Collection'),
	 '#access' => Drupal::currentUser()->hasPermission('administer rsvplist'),
	 '#group' => 'advance',
	 '#weight' => 100,
	 );

	 /** @var DrupalrsvplistEnablerService $enabler */
	 $enabler = Drupal::service('rsvplist.enabler');
	 $form['rsvplist']['rsvplist_enabled'] = array(
	 '#type' => 'checkbox',
	 '#title' => t('collect rsvp email'),
	 '#default_value' => $enabler->isEnabled($node),
	 );
	 foreach (array_keys($form['actions']) as $action) {
	  if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action] 
	  ['#type'] === 'submit'){
	  $form['actions'][$action]['#submit'][] = 'rsvplist_form_node_form_submit';
	  }
	  }
	 }
	}

Thanks!

Hi all,
I am in the middle of changing my opencart shop (1.5.5.1) from one host to another.
All files transferred & database uploaded to new server, but I get this error.

Parse error: syntax error, unexpected T_PUBLIC in /home/xxx/public_html/vqmod/vqcache/vq2-catalog_controller_common_seo_url.php on line 158

I guess there is an extra } somewhere in the code of vq2-catalog_controller_common_seo_url.php, but I cannot work out where .

Any help gratefully received !

Here is the code from that page

Code: Select all

<?php

class ControllerCommonSeoUrl extends Controller {

	public function index() {

		// Add rewrite to url class

		if ($this->config->get('config_seo_url')) {

			$this->url->addRewrite($this);

		}

		

		// Decode URL

		if (isset($this->request->get['_route_'])) {

			$parts = explode('/', $this->request->get['_route_']);

                        $this_route = $parts;
                        $this_route_multistore = $parts;
                        array_shift($this_route_multistore);
                        

			

			foreach ($parts as $part) {

				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($part) . "'");

				

				if ($query->num_rows) {

					$url = explode('=', $query->row['query']);

					

					if ($url[0] == 'product_id') {

						$this->request->get['product_id'] = $url[1];

					}

					

					if ($url[0] == 'category_id') {

						if (!isset($this->request->get['path'])) {

							$this->request->get['path'] = $url[1];

						} else {

							$this->request->get['path'] .= '_' . $url[1];

						}

					}	

					

					if ($url[0] == 'manufacturer_id') {

						$this->request->get['manufacturer_id'] = $url[1];

					}

					

					if ($url[0] == 'information_id') {

						$this->request->get['information_id'] = $url[1];

					}	

				} else {

					
                        if (is_file(DIR_APPLICATION . 'controller/' . implode("/", $this_route) . '.php'))  {
                        $this->request->get['route'] = implode("/", $this_route);
                        break;
                        } elseif (is_file(DIR_APPLICATION . 'controller/' . implode("/", $this_route_multistore) . '.php'))  {
                        $this->request->get['route'] = implode("/", $this_route_multistore);
                        break;
                        } else {
                        $this->request->get['route'] = 'error/not_found';
                        array_pop($this_route);
                        array_pop($this_route_multistore);
                        }
                        	

				}

			}

			

			
                        if (preg_match("/information//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (isset($this->request->get['information_id'])) {
				$this->request->get['route'] = 'information/information';
			} elseif (preg_match("/checkout//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/payment//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/feed//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/affiliate//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/account//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/total//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (isset($this->request->get['product_id'])) {
				$this->request->get['route'] = 'product/product';
			} elseif (isset($this->request->get['path'])) {
				$this->request->get['route'] = 'product/category';
			} elseif (isset($this->request->get['manufacturer_id'])) {
				$this->request->get['route'] = 'product/manufacturer/product';
			}
			









				$this->request->get['route'] = 'product/manufacturer/info';

			} elseif (isset($this->request->get['information_id'])) {

				$this->request->get['route'] = 'information/information';

			}

			

			if (isset($this->request->get['route'])) {

				return $this->forward($this->request->get['route']);

			}

		}

	}

	

	public function rewrite($link) {

		$url_info = parse_url(str_replace('&', '&', $link));

	

		$url = ''; 

		

		$data = array();

		

		parse_str($url_info['query'], $data);

		

		foreach ($data as $key => $value) {

			if (isset($data['route'])) {

				if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {

					$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");

				

					if ($query->num_rows) {

						$url .= '/' . $query->row['keyword'];

						

						unset($data[$key]);

					}					

				} elseif ($key == 'path') {

					$categories = explode('_', $value);

					

					foreach ($categories as $category) {

						$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");

				

						if ($query->num_rows) {

							$url .= '/' . $query->row['keyword'];

						}							

					}

					

					unset($data[$key]);

				}

			}

		}

	

		if ($url) {

			unset($data['route']);

		

			$query = '';

		

			if ($data) {

				foreach ($data as $key => $value) {

					$query .= '&' . $key . '=' . $value;

				}

				

				if ($query) {

					$query = '?' . trim($query, '&');

				}

			}



			return $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query;

		} else {

			
                        return preg_replace("/(index.php?route=|common/home)/", "", $link);
                        

		}

	}	

}

?>

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Parse error syntax error unexpected in opencart
  • Parse error syntax error unexpected in denwer
  • Parse error syntax error unexpected expecting variable
  • Parse error syntax error unexpected expecting end of file in
  • Parse error syntax error unexpected end of file in что значит

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

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