Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you assign values to constants with equal sign after using defined in php?

Tags:

php

constants

I know to define a constant, you do something like this

define("CONSTANT", "Hello world.");

if I want to change the value of the constant I would have to do define() again? Why couldn't I just do CONSTANT = "whatever"; after it has already been defined the first time?

like image 691
CodeCrack Avatar asked Jan 19 '12 19:01

CodeCrack


People also ask

What is a correct way of defining constants in PHP?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.

Which is not a rule for defining constants in PHP?

Constants cannot be defined by simple assignment, they may only be defined using the define() function. Constants may be defined and accessed anywhere without regard to variable scoping rules. Once the Constants have been set, may not be redefined or undefined.

Is it possible to redefine constants in PHP?

No, you cannot redefine a constant (except with runkit_constant_redefine), that's why is called CONSTANT.


2 Answers

The whole point of a constant is that it is constantly and always the same. You can not change a constant after you defined it.

Even using define("CONSTANT", "Hello world."); would return an error.

I just did it real fast to show you what you'd get:

Notice: Constant CONSTANT already defined in /Users/stokholm/test.php on line 3

Call Stack:
    0.0003     629992   1. {main}() /Users/stokholm/test.php:0
    0.0171     630232   2. define() /Users/stokholm/test.php:3
like image 167
Andreas Stokholm Avatar answered Nov 03 '22 00:11

Andreas Stokholm


Constants, as the name specifies, cannot be changed once defined. Use variables instead.

like image 43
Tim Cooper Avatar answered Nov 03 '22 01:11

Tim Cooper