PHP Constants

Constants are similar to variables except that, once they are defined, their values cannot be changed during the execution of the script. Constants are useful for defining values that are used throughout a program but should remain the same.


Defining Constants


  1. Using define() Function:


  • The define() function is used to create a constant.
  • Constants do not use the $ symbol when being defined or used.
  • They can store scalar values (strings, integers, floats, booleans) or arrays (from PHP 7).


         Syntax:


define(name, value)


  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
Example
<!DOCTYPE html>
<html>
<body>

<?php
// case-sensitive constant name
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Outputs: MyWebsite

?>

</body>
</html>

Try it yourself

Note

Constant name is case-sensitive.

       2. Using const Keyword (More common for defining class constants):


           Constants can also be defined using the const keyword

Example
<!DOCTYPE html>
<html>
<body>

<?php
const MYCAR = "Volvo";

echo MYCAR;
?>

</body>
</html>

Try it yourself

Note

const vs. define()

  • const cannot be created inside another block scope, like inside a function or inside an if statement.
  • define can be created inside another block scope.


PHP Constant Arrays


From PHP7, you can create an Array constant using the define() function.


Example
<!DOCTYPE html>
<html>
<body>

<?php

define("COLORS", ["Red", "Green", "Blue"]);
echo COLORS[0]; // Outputs: Red

?>

</body>
</html>

Try it yourself

Constants are Global


Constants are automatically global and can be used across the entire script, including within functions and methods.

Example
<!DOCTYPE html>
<html>
<body>

<?php
define("GREETING", "Welcome to whereisstuff.com!");

function myTest() {
echo GREETING;
}
myTest();
?>

</body>
</html>

Try it yourself

Note

Only defined constants are have Global scope.


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.