codescracker


php

PHP Constants



« Previous Tutorial Next Tutorial »


Constants in PHP are just like variables, but in case of constants, you can not redefine/undefine once you defined a constant in PHP script.

A valid constant name in PHP, must starts with a letter or underscore (but no dollar ($) sign before the name of the constant). Constants are automatically global across the entire PHP script:

Create a PHP Constant

To create a constant in PHP, use the function named define(). Here is the general form to create PHP constant:

define(name, value, case-insensitive)

Here is the explanation of the above parameters used in creating PHP constants:

PHP Constant Example

Here is an example, creates a PHP constant with a case sensitive name:

<!DOCTYPE html>
<html>
<body>

<?php
// case-sensitive constant name
define("GREETING", "Welcome to codescracker.com");
echo GREETING;
?>

</body>
</html>

Here is the output of the above PHP script:

PHP Constants Example

Here is another example, creates a constant with a case-insensitive name:

<!DOCTYPE html>
<html>
<body>

<?php
// case-insensitive constant name
define("GREETING", "Welcome to codescracker.com", true);
echo greeting;
?>

</body>
</html>

This is the output of the above PHP script:

PHP Constants Example

Constants in PHP are Global

As already told, that constants in PHP are automatically global and you can access to these constant across the entire PHP scripts, where they are created. Here is an example, creates and defined a constant outside the function, and used that constant inside the function:

<!DOCTYPE html>
<html>
<body>

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

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

</body>
</html>

It will display the following result:

PHP Constants Example

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test