JDelage
JDelage

Reputation: 13672

PHP - What are constants, are they good practice, and how do they differ from variables?

Beginner question...

How different is define("$a",365); from $a = 365;?

Thanks!

JDelage

Upvotes: 4

Views: 5078

Answers (4)

webbiedave
webbiedave

Reputation: 48897

A constant has a value that cannot change.

Named constants are usually considered bad practice in most languages (except in the case of compilation conditionals -- which PHP doesn't use, being interpreted -- or if it is assured they are centrally located, such as in config files) so it's best not to overuse them and, instead, look into using class constants where possible.

The reason for this is that it can make it more difficult to determine where a constant has been defined and makes it harder to avoid name clashes.

Upvotes: 1

dnagirl
dnagirl

Reputation: 20456

You define constants when you want a globally accessible value that never changes. For example, you might define a constant for website editor- something that has to appear on a lot of pages and would be a severe PITA to change if your company hired a different website editor.

So,

define('WEBEDITOR','Tom Jones');

then whereever you need to output 'Tom Jones', just echo WEBEDITOR.

A variable, is just that: variable. It changes.

Upvotes: 2

Silver Light
Silver Light

Reputation: 45922

Constants are meant to be used for values that do not change during program runtime. They are not stored in memory.

Good practice is to put static parameters that might be changed later in constants at the top of the file, so that they could be found and easily changed, if necessary, instead of find/replacing everything.

Another one: constant should always be in CAPITAL_LETTERS, so it would be clear that it is a constant.

Upvotes: 3

Alex Rashkov
Alex Rashkov

Reputation: 10015

If you define constant define("YEAR",365); you can't change it during execution time so YEAR will always be 365 no meter what. On the other hand variables can change their value during script execution also they have local scope, which means they are available just in the function file they are declared. Constants have global scope they can be accessed from all over the script.

http://php.net/manual/en/language.constants.php

http://planetozh.com/blog/2006/06/php-variables-vs-constants/

Upvotes: 6

Related Questions