- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP Constants
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.No | Parameter & Description |
---|---|
1 | name name of the constant. |
2 | value value of the constant may be any scalar value (integer, float, string etc) or array |
3 | case_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
Name | Description |
__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
<?php echo "Line no: " . __LINE__ . "
"; echo "file name : " . __FILE__ . "
"; echo "directory name: " . __DIR__ . "
"; function myfunction(){ echo "function name: " . __FUNCTION__ . "
"; } class myclass{ public function __construct() { echo __CLASS__ . "
"; } 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
Advertisements