LearnThatStack Ace your next interview
PHP · question
Question 9 of 82

How do you declare constants in PHP and what's the difference between define() and const?

beginner
← All PHP questions
Re-explain

Declare a constant with the const keyword or the define() function. The main difference is timing. const is defined at compile time, so it must sit at the top level of a file or inside a class. define() runs at runtime like any function call, so it works anywhere, including inside an if.

define('MAX_SIZE', 100);
const MIN_SIZE = 10;

// define() can be conditional
if ($condition) {
    define('DYNAMIC', 'value');
}
// const cannot be used conditionally

Because of that, const cannot appear inside functions, loops or if and try blocks. define() can also build the constant's name at runtime and accepts any expression as the value. Only const can declare class constants.

Prefer const for fixed values, and keep define() for constants that are conditional or have computed names.

Rewriting in plainer words…

This answer doesn't lend itself to a diagram - it reads best . No credits were charged.

Why there's no diagram: “”

The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓

The diagram below the answer is the concept . Jump to it ↓

Tailored explanation · switch back to · ·
What should the new diagram focus on?
How well did you know this?
AI:

Saved in this browser - sign in to keep your review list.

How should your speech become text?

Listening… your words appear above as you speak - tap Stop when you're done.

Recording · cr - tap Stop & transcribe when you're done.

Transcribing with AI…

Voice:

Keep going - a few more words and AI can grade it.

Interview lens

Likely follow-ups, what you can say, and the weak answers to avoid.

Sign in free to open it Free account - the lens opens as soon as you're back.

Want a quick review of the fundamentals? See the PHP cheatsheet.

← Back to all PHP questions
Pro · $10/mo

71 of 82 PHP answers are in Pro.

Full answers, code samples, and AI explanations that go simpler or deeper. Cancel anytime.

  • Full answers + code
  • AI explanations, simpler or deeper
  • 1,000 AI credits / month
  • Cancel anytime