EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP Constants

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP Constants

PHP Constants

Introduction to PHP Constants

PHP Constants are variables whose values once defined cannot be changed and these constants are defined without a $ sign in the beginning. PHP Constants are created using define() function. This function takes two parameters first is the name and second is the value of the constant defined.

The name of the constant starts using letters or underscores and not with a number. It can start with a letter or underscore followed by letters, underscores or numbers. The name is case-sensitive and in uppercase. After a constant is defined, it cannot be undefined or redefined again. It remains the same throughout the script and cannot be changed as the variables do.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax with Explanation

A constant is a name for a particular value. To define a constant, we have to use define() function and to get the value of the constant, we just need to specify the name.

Syntax:

define(name, value, case-insensitive);

where name is the name of the constant,

value is the value of the constant,

case-insensitive is either true or false, by default it is false.

Code:

define(‘TEXT’, ‘Hello World!’);
A constant can also be defined using const construct.
<?php
const MSG = "WELCOME";
echo MSG;
?>

How to Create Constants in PHP using Various Methods?

To create constants we have to use simple define function, which takes two parameters, first the name of the constant second the value to be stored. The name is by default in uppercase. It does not start with a $.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Example #1

Code:

<?php
//example to demonstrate constants
define("TEXT", "Hello World!");
echo TEXT;
?>

Output:

Hello World

In this example, we will be using a const construct to define a constant named TEXT. We have used const followed by name of the constant and then the value. It can be assigned a value using an assignment operator =.

Once we have defined the constant, to access the defined constant TEXT, we will echo the name with the constant keyword, as shown below.

Example #2

Code:

<?php
// program to demonstrate in PHP 7 using const keyword
const TEXT = 'PHP PROGRAMMING!';
echo TEXT;
echo constant("TEXT");
?>

Output:

PHP Constants-1.2

Example #3

In the below example, we are defining a TEXT constant with a value. Also in the same program, we have defined a function Demo(). We have declared the TEXT constant outside the function Demo. Here we see that we can access the constant TEXT from within the function. This means once you define the constant, it is globally available in the script.

Code:

<?php
//example to demonstrate the define constants globally
define("TEXT", "Hello World!");
echo TEXT;
function Demo() {
echo '<br>';
echo TEXT;
}
Demo();
?>

Output :

PHP Constants-1.3

Rules and Regulation for PHP Constants

The following are the rules to define PHP constants.

  • should not start with a $.
  • should not start with a number.
  • should not start with an underscore.
  • start with a letter and follow by numbers.
  • start with a letter and follow by underscore and numbers.

Let us look at the below statements.

<?php
define("TEXT","PHP");             //valid
define("TEXT1", "PHP");          //valid
define("1TEXT", "PHP");         //invalid
define("1_TEXT", "PHP");       //invalid
define("TEXT_1", "PHP");      //valid
define("__TEXT__", "PHP");   // valid but should be avoided
?>

Magic Constants

Starts with a double underscore

  • __LINE__
  • __FILE__
  • __FUNCTION__
  • __CLASS__
  • __METHOD__

1. __LINE__

This gives the current line number.

Code:

<?php
//example to demonstrate PHP magic constant __LINE__
echo 'I am at Line number '. __LINE__;
?>

Output:

PHP Constants-1.5

2.__FILE__

This gives the filename along with the file path of the file. It can be used to include a file in a script.

Code:

<?php
//example to demonstrate PHP magic constant __FILE__
echo 'FILE NAME '. __FILE__;
?>

Output:

PHP Constants-1.6

3. __FUNCTION__

This gives the name of the function in which it is declared. It is case sensitive.

Code:

<?php
// example to demonstrate the magic constant __FUNCTION__
function show() {
echo 'In the function '.__FUNCTION__;
}
show();
?>

Output:

PHP Constants-1.7

4. __METHOD__ , __CLASS__

This gives the name of the method and the name of the class in which it is declared. In the below example, we have defined the MainClass and two methods within it, the show method and the test method. Inside the show method, we have printed the __CLASS__ which gives the class name and inside test method we have printed the __METHOD__ which gives the method name, test.

Code:

<?php
// example to demonstrate the magic constant __CLASS__ and __METHOD__
class MainClass
{
function show() {
echo "<br>".__CLASS__;
}
function test() {
echo "<br>".__METHOD__;
}
}
$obj = new MainClass;
echo $obj->show();
echo $obj->test();
?>

Output:

__METHOD__ , __CLASS__ output

Conclusion

In this article, it is explained about PHP constants and magic constants with examples. These examples help to create own constants and use them in the script with the help of given syntax. This article also explains the rules on how to create PHP Constants, and then how to use it within the script with different methods.

Recommended Articles

This is a guide to PHP Constants. Here we discuss how to create constants in PHP along with syntax and examples. You may also look at the following articles to learn more –

  1. PHP Database Connection
  2. PHP Math Functions
  3. PHP Compiler
  4. PHP Switch Statement

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More