PHP Constants

PHPServer Side ProgrammingProgramming

Introduction

Constants are represented literally in an assignment expression such as $x=10 or $name="XYZ" where 10 and XYZ are numeric and string constants assigned to variables. In PHP, it is possible to define a constant with a user defined identifier with the help of define() function

Syntax

define ( string $name , mixed $value [, bool $case_insensitive = FALSE ] ) : bool

parameters

Sr.NoParameter & Description
1name
name of the constant.
2value
value of the constant may be any scalar value (integer, float, string etc) or array
3case_insensitive
Constant identifiers are case sensitive by default. If this parameter is set to true, name and NAME are treated similarly

Return Value

Function returns TRUE if definition is sucessful, else FALSE is returned

Example

Following example shows use of define() function to define constants

<?php
define("maxmarks",300);
define("pi", 3.142);
define("subjects",["phy", "che", "maths"]);
?>

magic constants

PHP has a large number of predefined constants but most of them will be enabled if corresponding extensions are installed. However, following constants - which are called magic constants - are always available

NameDescription
__LINE__The current line number of the file.
__FILE__The full path and filename of the file
__DIR__The directory of the file.
__FUNCTION__The function name, or {closure} for anonymous functions.
__CLASS__The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__The class method name.
__NAMESPACE__The name of the current namespace.

Following example demonstrates some of magic constants

Example

 Live Demo

<?php
echo "Line no: " . __LINE__ . "\n";
echo "file name : " . __FILE__ . "\n";
echo "directory name: " . __DIR__ . "\n";
function myfunction(){
   echo "function name: " . __FUNCTION__ . "\n";
}
class myclass{
   public function __construct() {
      echo __CLASS__ . "\n";
   }
   public function mymethod(){
      echo __METHOD__;
   }
}
$obj=new myclass();
$obj->mymethod();
?>

Output

Following result will be displayed

Line no: 2
file name : C:\xampp\php\testscript.php
directory name: C:\xampp\php
myclass
myclass::mymethod
raja
Published on 19-Sep-2020 18:30:15
Advertisements