Re: Cannot use const within try block

From: Date: Fri, 16 May 2014 15:08:59 +0000
Subject: Re: Cannot use const within try block
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-74264@lists.php.net to get a copy of this message
On 16 May 2014 15:44, Alain Williams <addw@phcomp.co.uk> wrote: > 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

« previous php.internals (#74264) next »