php oop constant

PHP OOP Constants

PHP constant has a fixed value and it can not be changed during the execution of the script. It will be created using the define() function or const keyword.

In other words, a PHP constant is an identifier(name) that has a fixed value and it can not be changed or undefined except the magic constant.

  • Once the constant is defined, its value can not be changed. It means it has global scope although it defines within the function.
  • Please keep in mind that the PHP constant does not have a $ sign before the constant name
  • A PHP constant name should start with a letter or underscore (_).

How To Declare PHP Constants

PHP constant can be defined in two ways.

  1. Using define() function
  2. Using const keyword

Creating PHP constant Using define() Function

To create PHP constant function, use the define() function. It defines constant at the run time.


  • name: It refers to a constant name.
  • value:It denotes constant value.
  • case-insensitive: Its default value is false. It denotes that the constant name is case-sensitive by default..

Source Code

Try it now

Creating PHP Constant Using constant Keyword

PHP provides another way to create a constant using the const keyword. Please keep in mind that the const keyword defines constant at compile-time and the constant name is also case-sensitive.

Source Code

Try it now

PHP Constant Arrays

Let us create an array constant using the the define() function.

Source Code

Try it now

How To Print Constant Value

There are two ways to display the constant value on the screen(browser).These are

  • 1.0 echo
  • 2.0 Constant() function

Constant() function

To display constant value, PHP also introduces a constant() function that is used to display the value of constant.

General Syntax


Source Code

Try it now

Difference Between Constant And Variables

  • Variable has a dollar sign ($) before the name while the constant name does not have a $ sign before the constant name.
  • The variable value can be changed later but the constant value can not be changed.
  • Variable follows scope rule while constant can be accessed anywhere without regard to variable scoping rules.