Const keyword

Const keyword in Php

The const keyword defines a constant.
Constants are much like variables, except for the following differences:
(i) It is define must be inside the class.
(ii) A constant’s value cannot be changed after it is set.
(iii) Constants do not have a dollar sign ($) before them.

Note:-
(i) Inside the class then values of the constants can be get using self keyword.
(ii) accessing the value outside the class you have to use Scope Resolution Operator ::

Example:-


<?php 
class Employee {
const sift = "Office timming is 10am to 6pm.";
const company_name="Company name is TCS.";
function displaysift_timming()
{
echo self::sift;
}
}
echo Employee::company_name;
$emp_obj = new Employee;
$emp_obj->displaysift_timming();
?>
Output:- Company name is TCS.
Office timming is 10am to 6pm.

Const keyword – Interview Questions

Q 1: What is const keyword in PHP?
Ans: It is used to define class constants.
Q 2: Can const be used outside a class?
Ans: No.
Q 3: Are constants created with const case-sensitive?
Ans: Yes.
Q 4: Can const values be changed?
Ans: No.
Q 5: When is const evaluated?
Ans: At compile time.

Const keyword – Objective Questions (MCQs)

Q1. const is used to declare ______.






Q2. Constants declared with const are ______.






Q3. const constants are defined ______.






Q4. const can be used inside ______.






Q5. Accessing a class constant uses ______.






Related Const keyword Topics