Parse error syntax error unexpected t string expecting t function

I get this error in my PHP code: PHP Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:Inetpubwwwrootwebrootwww.novotempo.org.brlibTwitter.php on line 54 The line in

Asked
13 years, 5 months ago

Viewed
31k times

I get this error in my PHP code:

PHP Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:Inetpubwwwrootwebrootwww.novotempo.org.brlibTwitter.php on line 54

The line in question:

define('DEBUG',false);

Searching the net I found that this usually occurs when you´re using PHP 4.xx, but I´m using 5.2.6 (Just checked it using phpinfo()).

I tried locally, and in two other external hosts, but it keeps returning the same message.

Why does this happen? How can I fix it?

legoscia's user avatar

legoscia

39.3k22 gold badges115 silver badges163 bronze badges

asked Aug 17, 2009 at 16:03

3

If you are trying to DEFINE something inside of a class but outside of a function, you are going to get this error.

(Normally the only place PHP will be looking for a function and not expecting a string is in a class, outside of a method)

IE: Your code should not look like this:

class myClass
{
    define("DEBUG", true);
    function myFunc()
     {
     }
}

answered Aug 17, 2009 at 16:08

Tyler Carter's user avatar

Tyler CarterTyler Carter

60.2k20 gold badges129 silver badges149 bronze badges

Thanks for this, resolved an annoying issue quite quickly for me.

I’d also like to add that the use of hyphens in constant names doesn’t work and is apparently expected behaviour. It seems as though the echo tries to evaluate mathematics (minus) on the words.

<?php
define('THIS-IS-A-TEST','Testing');
echo THIS-IS-A-TEST;
?>

Returns ‘0’

<?php
define('THIS_IS_A_TEST','Testing');
echo THIS_IS_A_TEST;
?>

Returns ‘Testing’

answered Apr 10, 2010 at 13:04

Lewis's user avatar

LewisLewis

212 bronze badges

1

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.

На перво странице сайта пишет: Parse error: syntax error, unexpected T_ELSE in /home/bitrix/www/index.php on line 25
Помогите понять где закралась оибка и как её исправить?

Содержимое файла <?
require($_SERVER[«DOCUMENT_ROOT»].»/bitrix/header.php»);
if(!$_REQUEST[«ORDER_ID»]){
$APPLICATION->SetTitle(«Ваша корзина»);
}else{
   $APPLICATION->SetTitle(«Заказ оформлен»);

    }
?>
<?
if($USER->IsAuthorized()){
   if(!isset($_GET[‘ORDER_ID’])){
       ?>
   <div class=»area-step2 container-fluid»>
       <div class=»wrapper»>
           <div class=»row»>
               <div class=»col-md-8″>
                   <h2>Оформление заказа <small>шаг 2 из 3</small></h2>

   <?}?>
   <?$APPLICATION->IncludeComponent(«bitrix:sale.order.ajax», «order», Array(
       «PAY_FROM_ACCOUNT» => «N»,    // Позволять оплачивать с внутреннего счета
           «ONLY_FULL_PAY_FROM_ACCOUNT» => «N»,    // Позволять оплачивать с внутреннего счета только в полном объеме
           «COUNT_DELIVERY_TAX» => «N»,    // Рассчитывать налог для доставки
           «ALLOW_AUTO_REGISTER» => «Y»,    // Оформлять заказ с автоматической регистрацией пользователя
           «SEND_NEW_USER_NOTIFY» => «N»,    // Отправлять пользователю письмо, что он зарегистрирован на сайте
           «DELIVERY_NO_AJAX» => «N»,    // Рассчитывать стоимость доставки сразу
           «DELIVERY_NO_SESSION» => «N»,    // Проверять сессию при оформлении заказа
           «TEMPLATE_LOCATION» => «.default»,    // Шаблон местоположения
           «DELIVERY_TO_PAYSYSTEM» => «d2p»,    // Последовательность оформления
           «USE_PREPAYMENT» => «N»,    // Использовать предавторизацию для оформления заказа (PayPal Express Checkout)
           «PROP_1» => «»,    // Не показывать свойства для типа плательщика «Физическое лицо» (s1)
           «ALLOW_NEW_PROFILE» => «Y»,    // Разрешить множество профилей покупателей
           «SHOW_PAYMENT_SERVICES_NAMES» => «Y»,    // Отображать названия платежных систем
           «SHOW_STORES_IMAGES» => «N»,    // Показывать изображения складов в окне выбора пункта выдачи
           «PATH_TO_BASKET» => «/order/»,    // Страница корзины
           «PATH_TO_PERSONAL» => «index.php»,    // Страница персонального раздела
           «PATH_TO_PAYMENT» => «payment.php»,    // Страница подключения платежной системы
           «PATH_TO_AUTH» => «/auth/»,    // Страница авторизации
           «SET_TITLE» => «Y»,    // Устанавливать заголовок страницы
           «DISABLE_BASKET_REDIRECT» => «Y»,    // Оставаться на странице, если корзина пуста
           «PRODUCT_COLUMNS» => «»,    // Дополнительные колонки таблицы товаров заказа
       ),
       false
   );?>

   <?
if($USER->IsAuthorized()){
   if(!isset($_GET[‘ORDER_ID’])){
       ?>
   <?$APPLICATION->IncludeComponent(
       «bitrix:sale.basket.basket»,  
       «»,  
       array(
           «COLUMNS_LIST» => array(
               0 => «NAME»,
               1 => «PROPS»,
               2 => «DELETE»,
               3 => «PRICE»,
               4 => «QUANTITY»,
               5 => «SUM»,
           ),
           «PATH_TO_ORDER» => «/order/»,
           «HIDE_COUPON» => «N»,
           «PRICE_VAT_SHOW_VALUE» => «N»,
           «USE_PREPAYMENT» => «N»,
           «QUANTITY_FLOAT» => «N»,
           «SET_TITLE» => «N»,
           «ACTION_VARIABLE» => «action»
       ),
       false  
   );?>
   <?
       }}
           ?>
   <?if(!isset($_GET[‘ORDER_ID’])){?>
               </div>
               <div class=»col-md-4 «>
                   <?$APPLICATION->ShowViewContent(‘cart’);?>

                                           <?$APPLICATION->IncludeComponent(«bitrix:news.list», «cart_faq», Array(
                       «ACTIVE_DATE_FORMAT» => «d.m.Y»,    // Формат показа даты
                           «ADD_SECTIONS_CHAIN» => «N»,    // Включать раздел в цепочку навигации
                           «AJAX_MODE» => «N»,    // Включить режим AJAX
                           «AJAX_OPTION_ADDITIONAL» => «»,    // Дополнительный идентификатор
                           «AJAX_OPTION_HISTORY» => «N»,    // Включить эмуляцию навигации браузера
                           «AJAX_OPTION_JUMP» => «N»,    // Включить прокрутку к началу компонента
                           «AJAX_OPTION_STYLE» => «Y»,    // Включить подгрузку стилей
                           «CACHE_FILTER» => «N»,    // Кешировать при установленном фильтре
                           «CACHE_GROUPS» => «Y»,    // Учитывать права доступа
                           «CACHE_TIME» => «36000000»,    // Время кеширования (сек.)
                           «CACHE_TYPE» => «A»,    // Тип кеширования
                           «CHECK_DATES» => «Y»,    // Показывать только активные на данный момент элементы
                           «DETAIL_URL» => «»,    // URL страницы детального просмотра (по умолчанию — из настроек инфоблока)
                           «DISPLAY_BOTTOM_PAGER» => «Y»,    // Выводить под списком
                           «DISPLAY_DATE» => «Y»,    // Выводить дату элемента
                           «DISPLAY_NAME» => «Y»,    // Выводить название элемента
                           «DISPLAY_PICTURE» => «Y»,    // Выводить изображение для анонса
                           «DISPLAY_PREVIEW_TEXT» => «Y»,    // Выводить текст анонса
                           «DISPLAY_TOP_PAGER» => «N»,    // Выводить над списком
                           «FIELD_CODE» => array(    // Поля
                               0 => «»,
                               1 => «»,
                           ),
                           «FILTER_NAME» => «»,    // Фильтр
                           «HIDE_LINK_WHEN_NO_DETAIL» => «N»,    // Скрывать ссылку, если нет детального описания
                           «IBLOCK_ID» => «1»,    // Код информационного блока
                           «IBLOCK_TYPE» => «news»,    // Тип информационного блока (используется только для проверки)
                           «INCLUDE_IBLOCK_INTO_CHAIN» => «N»,    // Включать инфоблок в цепочку навигации
                           «INCLUDE_SUBSECTIONS» => «Y»,    // Показывать элементы подразделов раздела
                           «MESSAGE_404» => «»,    // Сообщение для показа (по умолчанию из компонента)
                           «NEWS_COUNT» => «4»,    // Количество новостей на странице
                           «PAGER_BASE_LINK_ENABLE» => «N»,    // Включить обработку ссылок
                           «PAGER_DESC_NUMBERING» => «N»,    // Использовать обратную навигацию
                           «PAGER_DESC_NUMBERING_CACHE_TIME» => «36000»,    // Время кеширования страниц для обратной навигации
                           «PAGER_SHOW_ALL» => «N»,    // Показывать ссылку «Все»
                           «PAGER_SHOW_ALWAYS» => «N»,    // Выводить всегда
                           «PAGER_TEMPLATE» => «.default»,    // Шаблон постраничной навигации
                           «PAGER_TITLE» => «Новости»,    // Название категорий
                           «PARENT_SECTION» => «»,    // ID раздела
                           «PARENT_SECTION_CODE» => «»,    // Код раздела
                           «PREVIEW_TRUNCATE_LEN» => «»,    // Максимальная длина анонса для вывода (только для типа текст)
                           «PROPERTY_CODE» => array(    // Свойства
                               0 => «»,
                               1 => «»,
                           ),
                           «SET_BROWSER_TITLE» => «N»,    // Устанавливать заголовок окна браузера
                           «SET_LAST_MODIFIED» => «N»,    // Устанавливать в заголовках ответа время модификации страницы
                           «SET_META_DESCRIPTION» => «N»,    // Устанавливать описание страницы
                           «SET_META_KEYWORDS» => «Y»,    // Устанавливать ключевые слова страницы
                           «SET_STATUS_404» => «N»,    // Устанавливать статус 404
                           «SET_TITLE» => «N»,    // Устанавливать заголовок страницы
                           «SHOW_404» => «N»,    // Показ специальной страницы
                           «SORT_BY1» => «ACTIVE_FROM»,    // Поле для первой сортировки новостей
                           «SORT_BY2» => «SORT»,    // Поле для второй сортировки новостей
                           «SORT_ORDER1» => «DESC»,    // Направление для первой сортировки новостей
                           «SORT_ORDER2» => «ASC»,    // Направление для второй сортировки новостей
                       ),
                       false
                   );?>
               </div>
           </div>
       </div>
   </div>
   <?}?>
<?} else{
   LocalRedirect(«/login/»);
}?>
<?require($_SERVER[«DOCUMENT_ROOT»].»/bitrix/footer.php»);?>

<?php

namespace CloudwaysMyModuleControllerIndex;

use MagentoFrameworkAppActionAction;

use MagentoFrameworkAppActionContext;

use MagentoFrameworkViewElementMessages;

use MagentoFrameworkViewResultPageFactory;  

class Index extends MagentoFrameworkAppActionAction
{

    /** @var PageFactory $resultPageFactory */
    protected $resultPageFactory;

     /**
     * Result constructor.
     * @param Context $context
     * @param PageFactory $pageFactory
     */
    public function __construct(Context $context, PageFactory $resultPageFactory)
    {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    /**
     * Blog Index, shows a list of recent blog posts.
     *
     * @return MagentoFrameworkViewResultPageFactory
     */
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Custom Front View'));
        return $resultPage;

    }
}

Qaisar Satti's user avatar

Qaisar Satti

32.3k18 gold badges81 silver badges135 bronze badges

asked Apr 5, 2017 at 6:01

7

it might be space issue. I am getting following error and resolved by removing space.

syntax error, unexpected ‘ public’ (T_STRING), expecting function (T_FUNCTION) in /var/www/html/mage2/app/code/Mymodule/Custommodule/Controller/Index/Index.php on line 6

answered Aug 6, 2018 at 10:15

Niranjan Gondaliya's user avatar

0

When you copy code from some web it includes special character in the lines you have to remove these invisible special characters from lines at beginning or ending. where error pointing like:

Parse error: syntax error, unexpected 'class' (T_CLASS) in /opt/lampp/htdocs/mage225/app/code/Progos/ThemeChanges/Observer/Product/Data.php on line 10

and

Parse error: syntax error, unexpected '$product' (T_VARIABLE) in /opt/lampp/htdocs/mage225/app/code/Progos/ThemeChanges/Observer/Product/Data.php on line 21

Can be resolved by removing all before and after the line.

answered Sep 19, 2018 at 9:42

Hassan Ali Shahzad's user avatar

In this tutorial, we’re going to provide details regarding the error message syntax error, unexpected T_STRING, including the meaning and ways to fix it.

What Does the Error Mean?

The error message Parse error: syntax error, unexpected T_STRING usually appears when a .html file starts with an <? tag. This confuses our Apache web server when attempting to execute the code as it is a PHP script.

syntax-error-unexpected-t-string 1

How Can I Overcome this Problem?

This issue can be easily resolved in five easy steps:

    1. Log into your AwardSpace hosting account.
    2. Visit the PHP Settings section.
    3. Click on the here button.
    4. Locate the line short_open_tag = On and change it to short_open_tag = Off .

syntax-error-unexpected-t-string 2

  1. Press Save to save the changes you have just made.

What If I Do Not Have Access to the PHP.ini File? Am I Still Able to Fix the Error?

If, for some reason, you’re unable to access the PHP.ini section or your account type does not give you enough rights to modify the PHP.ini file, you can still resolve the error with the use of a text file, called .htaccess.

The steps you need to perform are the following:

    1. Sign in to your Hosting Control Panel.
    2. Navigate to the File Manager section.
    3. Create a .htaccess file in your domain directory with the below code:

RemoveHandler .html .htm

The screenshot below illustrates how your code should look like:

syntax-error-unexpected-t-string 3

After you follow the above steps, clear your browser’s cache, and then reload your HTML page. No further parse errors will appear when visiting your website in a browser.

syntax-error-unexpected-t-string 4


Keep reading

  • Why my website or parts of it look misplaced or broken on some browsers or devices?

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

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

  • Parse error syntax error unexpected t string expecting t constant encapsed string or
  • Parse error syntax error unexpected t object operator
  • Parse error syntax error unexpected public
  • Parse error syntax error unexpected in opencart
  • Parse error syntax error unexpected in denwer

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

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