PHP Constants

Table of Contents

PHP 1 Create a PHP Constant

<h2>php Constants-Create_a_PHP_Constant</h2> <p>To create a constant, use the define() function.</p> <?php // case-sensitive constant name define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?>

Example 1

Result View Example

PHP 2 const Keyword

<h2>php Constant-const_Keyword</h2> <p>You can also create a constant by using the const keyword.</p> <?php // Create a case-sensitive constant with the const keyword: const MYCAR = "Volvo"; echo MYCAR; ?>

Example 2

Result View Example

PHP 3 Constant Arrays

<h2>Constant Arrays</h2> <p>From PHP7, you can create an Array constant using the define() function.</p> <?php define("cars", [ "Alfa Romeo", "BMW", "Toyota" ]); echo cars[2]; ?>

Example 3

Result View Example

PHP 4 Constants are Global

<h2>php Constants-Constants_are_Global</h2> <p>Constants are automatically global and can be used across the entire script.</p> <?php // This example uses a constant inside a function, even if it is defined outside the function: define("GREETING", "Welcome to W3Schools.com!"); function myTest() { echo GREETING; } myTest(); ?>

Example 4

Result View Example

Document

Document in project

You can Download PDF file.

Reference