Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

constants
php

What are PHP constants?

Educative Answers Team

PHP is a server-side scripting language used to develop static and dynamic websites or certain web applications.

Constants in PHP

A constant is an identifier that cannot be changed during the course of the script. Changing the value stored inside a constant will result in an error. There are many types of constants in a computer; one commonly used value is pi. Whatever the course of a program, the value of pi is one such example that cannot be changed at any point in the script.

Generally, constants are global across the entire script.

Create a PHP Constant

Variables in PHP are defined using the $ sign:

$x = 5;
$str = "Hello World";

However, to define a constant, we will use the define() function.

Syntax:

define(name, value)
/*
Parameters: name: Specifies the name/identifier of the constant. 

e.g pi, a, b, c.

value: Specifies the value to be stored in the constant.
*/

Code

<?php
// define a constant a with value 2;
define(a,2);
echo a; // print a
echo "\n";

// define a constant string h
define("h","New string");
echo h; // print h
echo "\n";

//define a constant boolean value x;
define(x,true);
echo x; //print x

// the output of the code will show a warning that constants are used
// therefore they cannot be changed. 
?>

RELATED TAGS

constants
php
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring