What Is An Constants In PHP Language Tutorial?

PHP 8 , PHP

Nicesnippets

370

13-08-2021


What Is An Constants In PHP Language Tutorial?

Hi guys,

Today i will explained What is Constants In PHP and how to use in php language. This example is so easy to use in php.

Constants is a one type variables except that once they are defined they cannot be changed or undefined. A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name).

So let's start to the example.

Syntax


define(name, value, case-insensitive)

Parameters

-name: Specifies the name of the constant

-value: Specifies the value of the constant

-case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

Create A Constant with A Case-sensitive Name:

<?php

// case-sensitive constant name

define("GREETING", "Welcome to Nicesnippets.com!");

echo GREETING;

?>

Output

Welcome to Nicesnippets.com!

Create A Constant With A Case-insensitive Name:

<?php

// case-insensitive constant name

define("GREETING", "Welcome to Nicesnippets.com!", true);

echo greeting;

?>

Output

Welcome to Nicesnippets.com!

PHP Constant Arrays

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

Create an Array constant:

<?php

define("cars", [

"Alfa Romeo",

"BMW",

"Toyota"

]);

echo cars[0];

?>

Output

Alfa Romeo

Constants are Global

Constants are automatically global and can be used across the entire script.

This example uses a constant inside a function, even if it is defined outside the function:

<?php

define("GREETING", "Welcome to Nicesnippets.com!");

function myTest() {

echo GREETING;

}

myTest();

?>

Output

Welcome to Nicesnippets.com!

Now you can check your own.

I hope it can help you...


Recommended Posts