The code below gives me: PHP Parse error: syntax error, unexpected T_CONST
in ...
try {
const XXX = 12;
echo "XXX = " . XXX . "\n";
}catch (ErrorException $e) {
echo "error {$e->getMessage()}\n";
}
It works if I put the 'cost' before/outside the 'try'.
It also works if I replace the const line by:
define('XXX', 'twelve');
or
include "testdef.php";
where testdef.php contains:
const XXX = 12;
I cannot find this behaviour documented.
a) If there is no good reason for this restriction - can it be removed.
or
b) If there is good reason for it can this be documented.
Regards
--
Alain Williams
Linux/GNU Consultant - Mail systems, Web sites, Networking, Programmer, IT Lecturer.
+44 (0) 787 668 0256 http://www.phcomp.co.uk/
Parliament Hill Computers Ltd. Registration Information: http://www.phcomp.co.uk/contact.php
#include <std_disclaimer.h
> The code below gives me: PHP Parse error: syntax error, unexpected `T_CONST` in ...
>
> try {
> const XXX = 12;
>
> echo "XXX = " . XXX . "\n";
>
> }catch (ErrorException $e) {
> echo "error {$e->getMessage()}\n";
> }
>
> It works if I put the 'cost' before/outside the 'try'.
>
> It also works if I replace the const line by:
>
> define('XXX', 'twelve');
>
> or
>
> include "testdef.php";
>
> where testdef.php contains:
>
> const XXX = 12;
>
Defining constants using const is handled at compile time. Because of
this, it cannot be dependent on branches that are only processed at
run time. When you include a file, this creates a new "compile-time"
for the included file, so the operation succeeds.
`define()` is a regular function call evaluated at run time.
As such if you want a constant defined conditionally then you'll need
to use `define()`
> I cannot find this behaviour documented.
>
> a) If there is no good reason for this restriction - can it be removed.
>
> or
>
> b) If there is good reason for it can this be documented.
This behaviour is documented; to quote the note at http://php.net/const
"As opposed to defining constants using `define()`, constants defined
using the const keyword must be declared at the top-level scope
because they are defined at compile-time. This means that they cannot
be declared inside functions, loops or if statements."
I will update the note shortly to include try/catch blocks.
Thanks, Chris