1

What is difference in defining the variables like

define('SITENAME', "My Site");

and

$sitename = "My Site";

which way is better to define configuration variables (such as site name/urls etc.)? Thanks.

1
  • to add to the answers, constants have global scope whereas variables don't by default Commented Mar 28, 2011 at 22:23

5 Answers 5

5

This is the definition of a constant:

define('SITENAME', "My Site");

You cannot change the value, and you don't refer to it with a $ prefix. In general, it has nothing at all to do with variables.

This is a variable:

$sitename = "My Site";

For values which are not expected to change during execution of your PHP script (e.g. some configuration parameters) it might be better to define constants. Also, constants have global scope (you cannot, and don't need, to make them global).

On the other hand, keep in mind that you cannot iterate over a bunch of constants as you can iterate over an array of values. For example, you cannot pass a $config array and read multiple values from it without knowing which values you are interested in beforehand.

Usually constants are used for options that may influence the behavior of the whole of your application, for example:

define('DEBUG', 1);

For other cases, variables are more convenient so they are commonly used even when technically their values are constant for the duration of your application's run.

Sign up to request clarification or add additional context in comments.

Comments

3

The former is a definition of a constant, the latter the definition of a variable. The former can't be changed during runtime anymore (at least not on a standard install), whereas the latter can.

Thus define is probably more appropriate for configuration, as these values will not change during script runtime.

Comments

0

The difference is that the "define"-function is not for defining variables it's for constants.

A variable has the ability to change value(s) but the constant stay the same through the code.

Comments

0

define() seems to be for constants, where as $name is for variables: http://php.net/manual/en/function.define.php

Comments

0

define is used to define CONSTANTS. Those that "cannot change".

The second one is used to define variables. Is the most common way to make a program works.

In my expirience, to define config settings is better to use constants, put all them in a single config file for simple access.

More info:

Variables: http://php.net/manual/en/language.variables.php Constants: http://php.net/manual/en/language.constants.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.