Workaround For Basic Syntax Not Being Parsed

Workaround for basic syntax not being parsed

When declaring a class constant or property in PHP you can only specify a primitive values for default values. So for instance, this class declaration won't work:

class TEST {
const ABC = 2 * 4;
const DEF = some_function();
static $GHI = array(
'key'=> 5 * 3,
);
}

But this class declaration will:

class TEST {
const ABC = 8;
static $GHI = 15;
}

These rules apply to default values for class constants/properties - you can always initialize other variables with the results of an expression:

$a= array(
'a'=> 1 * 2,
'b'=> 2 * 2,
'c'=> 3 * 2,
);

The reason for this class declaration behavior is as follows: expressions are like verbs. They do something. Classes are like nouns: they declare something. A declarative statement should never produce the side-effects of an action statement. Requiring primitive default values enforces this rule.

With this in mind we can refactor the original class as follows:

class SDK
{

static protected $_types= null;

static public function getType($type_name) {
self::_init_types();
if (array_key_exists($type_name, self::$_types)) {
return self::$_types[$type_name];
} else {
throw new Exception("unknown type $type_name");
}
}

static protected function _init_types() {
if (!is_array(self::$_types)) {
self::$_types= array(
'STRING_NONE'=> 1 << 0,
// ... rest of the "constants" here
'STRING_HOSTS'=> 1 << 6
);
}
}

function __construct($fString = null) {
if (is_null($fString)) {
$fString= self::getType('STRING_NONE') & self::getType('STRING_HOSTS');
}
var_dump($fString);
}

}

$SDK &= new SDK(SDK::getType('STRING_HOSTS'));

Array class property

Class properties must have constant initial values. The concatenation of those two strings is NOT a constant value.

From the documentation:

[Property] declaration may include an initialization, but this initialization must be a constant value -- that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

You could put the property initialisation in your constructor:

public function __construct()
{
$this->arr = array(
'hw' => self::HELLO . 'world'
);
}

Syntax error when trying to create array of anonymous functions

You must define the methods in the constructor, or some other method, not directly in the class member declaration.

class User extends Model {

public $hasOne = array('UserSetting');

public $validate = array();

public $virtualFields = array();

public function __construct() {
$this->virtualFields = array(
'fullname' => function () {
return $this->fname . ($this->mname ? ' ' . $this->mname : '') . ' ' . $this->lname;
},
'official_fullname' => function () {

}
);
}
}

While that works, PHP's magic method __get() is better suited to this task:

class User extends Model {

public $hasOne = array('UserSetting');

public $validate = array();

public function __get($key) {
switch ($key) {
case 'fullname':
return $this->fname . ($this->mname ? ' ' . $this->mname : '') . ' ' . $this->lname;
break;

case 'official_fullname':
return '';
break;
};
}
}

PHP parse/syntax errors; and how to solve them


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.

Syntax error in JS intended for website flashing fix

In JavaScript, strings cannot be broken up into multiple lines. The new line character is not a valid string character. You will have to close the string on each line and add the string concatenation operator after each line that is continued on the next line (or before each line that is a continuation of the previous line, like so:

if (document.getElementById)
{
document.write(
'<style type="text/css" media="screen">' +
'#element1, .element2 {display:none;}'
+ '</style>');
}

This will get rid of the error, but it will not achieve the desired effect of hiding elements. document.write automatically calls document.open() if an HTML document has already been opened (which it has, if the script is executing.) document.open will wipe out the contents of the page, including the script that contains that code. You will be left with a blank page.

As @Chris says, you can include script tags in the output of a php script simply by writing the script outside of the php parsing context. i.e.

?>
<head>
<!-- other stuff -->
<script type="text/javascript">// type="text/javascript" is only needed for browser versions that do not support HTML5
// place code here
</script>
<!-- other stuff -->
</head>
<?php

On the other hand, if you wish to include a separate, external JavaScript file, replace that script tag in the code snippet above with

<script src="[absolute or relative path to script]" type="text/javascript">
</script>

Note that script tags are not self-closing, so even though this script tag has no contents, you cannot use the self closing tag syntax, as in <script ... />

As for the problem of how to handle the flickering problem, this Stack Overflow post may be helpful:

Page Transitioning - Ways to Avoid the "flicker"

How to fix the YAML syntax error: did not find expected '-' indicator while parsing a block?

You don't have 32 lines in your file (probably because you stripped non-essential data out of the example), but the indentation level points to the line with fi.

Actually the problem starts earlier and what you want to do is specify the action to take as a multi-line string. You can specify those in YAML in multiple ways but the cleanest is to use the literal scalar indicator "|", which preserves newlines:

install:

- |
if [[ "${TEST_PY3}" == "false" ]]; then
pip install Cython;
python setup.py build; # To build networkx-metis
mkdir core; # For the installation of networkx core
cd core;
git clone https://github.com/orkohunter/networkx.git;
cd networkx/;
git checkout addons;
python setup.py install;
cd ..;
fi

There is no automatic YAML re-indentation tool for these kind of errors.

Reindenters for Python take working code and make the indentation consistent (replacing TABs, always same indent per level). Python code re-indentation on code with syntax errors, either doesn't work or might produce non-correct results.

Reindenters for YAML face the same problem: what to do if the input doesn't make sense (and what is clear to you and me, is not always clear to a program). Just making everything that doesn't parse well into a multi-line scalar is not a generic solution.

Apart from that, most YAML parsers throw away some information on reading in the files, that you would not want to get lost by re-indenting, including EOL comments, hand crafted anchor names, mapping key ordering, etc. All without violating the requirements in the specification.

If you want to uniformly indent your (correct) YAML you can use the yaml utility that is part of the [ruamel.yaml][2] package (disclaimer: I am the author of that package). Your original input used with yaml round-trip .travis.yml would give:

 ...
in "<byte string>", line 3, column 3:
- if [[ "${TEST_PY3}" == "false" ...
^
expected <block end>, but found '<scalar>'
in "<byte string>", line 6, column 7:
mkdir core; # For the installati ...

Unfortunately not much more helpful in finding the error, the correct .travis.yml version run through yaml round-trip .travis.yml will tell you that it stabilizes on the second round-trip (ie. on the first the extra whitespace is lost). And yaml round-trip .travis.yml --save gives you:

install:
- |
if [[ "${TEST_PY3}" == "false" ]]; then
pip install Cython;
python setup.py build; # To build networkx-metis
mkdir core; # For the installation of networkx core
cd core;
git clone https://github.com/orkohunter/networkx.git;
cd networkx/;
git checkout addons;
python setup.py install;
cd ..;
fi

Please note that in this # TO build networkx-metis is not a YAML comment. It is just part of the multi-line string. A comment on a line before the first or after the last would however be preserved.

How to fix syntax error in basic input function

Remove "grade" after the else, so the last two lines read:

else: 
print("You failed :(")


Related Topics



Leave a reply



Submit