-2

I am trying to define a session variable as constant ...

define("MY_VAR", $_SESSION['variable_name']);

I start the session before accessing this constant

However, when I try to change the value of the variable ...

MY_VAR = "xyz"

... I get following message

"Parse error: syntax error, unexpected '=' in"

I am not sure what's happening here. It would be great if someone could shed some light on this.

Note: Instead, if I use $_SESSION['variable_name'] at all places where I used MY_VAR, the code works fine

deceze
  • 510,633
  • 85
  • 743
  • 889
DesV
  • 9
  • 3
  • 3
    You cannot *assign to constants.* Constants are, well, **constant.** If they were mutable they'd be *variables.* – deceze Oct 30 '17 at 11:50
  • It looks like you're trying to use a constant as a reference to another variable - that's not what they're for at all. – iainn Oct 30 '17 at 11:52
  • Thanks iainn ! That is the reply/answer that I was looking for ... is there anything you would recommend to use as "reference" ... The thing I can think of is just creating a variable to store the new value and updating the session variable at the end ... but I was looking for a "reference" approach rather so that I don't have to mention the session variable in every page. – DesV Oct 30 '17 at 12:05
  • You can assign a reference variable in PHP using `=&` - [have a read through the docs here](http://php.net/manual/en/language.references.whatdo.php). Constants are entirely separate from this. – iainn Oct 30 '17 at 12:07
  • @iainn : Thanks a lot! I will go through it. – DesV Oct 30 '17 at 12:13
  • @iainn: Just an update ... I read through the link you shared. I think that won't solve my purpose, as it seems that it won't update my session variable value directly. I think I should simply write a function to address this. Thanks so much for your help!! – DesV Oct 30 '17 at 12:28

1 Answers1

2

The point of constants is they are constant.

Once set you can't change them.

Scoots
  • 3,048
  • 2
  • 21
  • 33
  • Thanks for your reply. – DesV Oct 30 '17 at 11:51
  • Please correct me if I am wrong but my understanding is that the **constant**'s value is the name of the SESSION variable; variable's value can be changed by referring to the constant. So for example ... let's say, *$_SESSION['variable_name'] = "abc"* I create a constant *define("MY_CONSTANT", $_SESSION['variable_name']);* and then I change *MY_CONSTANT="xyz";* wouldn't that make *$_SESSION['variable_name'] = "xyz"*? – DesV Oct 30 '17 at 11:56
  • @DesV Constants can not be changed. `As the name suggests, that value cannot change during the execution of the script` -http://php.net/manual/en/language.constants.php – chris85 Oct 30 '17 at 12:01
  • Thanks! so I got that I was using it in a wrong way. But "iainn" (above) understood what I was trying to do and looking for... – DesV Oct 30 '17 at 12:10