Define keyword

Define keyword in Php

The define() function defines a constant.
Constants are much like variables, except for the following differences:
(i) Using define() INSIDE a class definition does not work..
(ii) A constant’s value cannot be changed after it is set.
(iii) Constants do not have a dollar sign ($) before them.
(iv) Constant values can only be strings and numbers.

Syntax:-
bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

Parameter
Description
$name
Required
$value
Required
$case_insensitive
Optional(false)

Note:-
(i) A valid constant name starts with a letter or underscore.
(ii) define keyword is used for global.

Example:-


<?php 
define("IMAGE_WIDTH", 400px);
echo IMAGE_WIDTH; // outputs:- 400px
echo IMAGE_width; // outputs:- "IMAGE_width" and issues a notice

define("IMAGE_WIDTH", 400px, true);
echo IMAGE_WIDTH; // outputs 400px
echo IMAGE_width; // outputs 400px
?>

Define keyword – Interview Questions

Q 1: What is define() in PHP?
Ans: A function used to define constants.
Q 2: Can define() be used inside a class?
Ans: Yes.
Q 3: Is define() evaluated at runtime?
Ans: Yes.
Q 4: Can constants created by define() be global?
Ans: Yes.
Q 5: Difference between define() and const?
Ans: define() is runtime; const is compile-time.

Define keyword – Objective Questions (MCQs)

Q1. Which function defines a global constant?






Q2. Constants created with define() are ______.






Q3. define("PI", 3.14); creates a constant accessible ______.






Q4. Can define() create constants at runtime?






Q5. Accessing a constant created by define() uses ______.






Related Define keyword Topics