On Wed, Mar 29, 2017 at 11:10 PM, dmitr y <d726...@gmail.com> wrote:

> Hello, dear coders.
> I'm using php for a year and it's being my favourite language. Also I'm
> using some bookkeping languages which is based on php syntax but ';' on the
> end of the line is not neccesary on it.
> So I can't understand why syntax needs symbol ';' on the end of every line,
> if it also ends by 0Ch and 0Dh. Is there a possibility to interpretate php
> code without ';' on the end of the line, and make it not necessary?
>
> Maybe some compilation parameter or directive at code?
>
> Best regards,
> Dmitry
>

Dmitry,

It is not necessary to end each line with a semicolon (the ';'), it is
however necessary to terminate each statement (or instruction) with one.
It's very common to only have one statement per line; which is why is seems
that it is required on every line.

There are several places this is not the case:

- Any block opening/close: e.g.

if/while/for/foreach ... {
   // or it's close, or a comment for that matter!
}

- An unfinished statement:

echo $foo .
         $bar // concat (.) operator can be here, as above, or on the next
line:
         . $baz; // only semicolon here, to finish the statement

- Preceding a closing PHP tag (?>) as this also terminates a statement:

echo $foo ?>
<?php
// or
echo $bar
?>


Alternatively, you may have MORE than one statement per line:

- echo $foo; return $bar;

- syslog(LOG_ERR, "Something went wrong!"); exit;

- header("Location: /foo/bar"); exit;

Notice each of these has two statements. (Note: I don't think any of these
are particularly good ways to write readable code, but they are all
syntactically valid code).

While I know some languages make semicolons optional (javascript), or omit
them entirely (python),  semicolons in PHP will not be going away (or
optional) any time soon.

Even a language like Go where they are optional, and largely discouraged,
it can be used to explicitly allow the initialization of a local (only
exists in the scope of the if statement) variable prior to the condition:

if err := DoSomething(); err != nil {
// initialization before    ; condition {
      return err // no semicolon necessary
}

I hope this helps!

- Davey

Reply via email to