pTutorial

New way to learn PHP

PHP 5 Class Constants

Class Constants

Class constant is a special identifier that hold fixed values throughout the running of your PHP script. To create a class constant, use the keyword const followed by the property name (without $ sign), as shown below:

Use of class constant

Class constant is usually used for the configuration value like the database user name.

Syntax

Class Student
{
const MXIMUM_MARKS = 100;
}
C

It is a convention to all class const must be in uppercase letter.


You can access class constant by using the scope resolution operator (::) same as static properties.

MyClass::staticConstant;

PHP class constant example

<?php

class Login
{
    const Login_NAME = "John Doe";
    const PASSWORD = "Admin123";
}

echo "User name: " . Login::Login_NAME."
"; echo "Password: " . Login::PASSWORD."
"; ?>

Output

User name: John Doe
Password: Admin123

In the Login class, Login_NAME and PASSWORD are the class constant. You can easily access with the help of scope resolution operator, as shown above.

Example

<?php

class Computer 
{
	const NAME = "Sony Vaio";
 
	public function display()
	 {
		echo " Name of Compuer Brand : " . Computer::NAME;
	 }
 
}
 
$obj = new Computer();
$obj->display();

?>

Output

Name of Compuer Brand : Sony Vaio

Example of class constant

The below example demonstrates the ability of accessing a constant within the class and outside the class.

<?php

class Student 
{
const ROLL = 38;
public $fi_name;
 
function Student($fi_name1)
{
    $this->fi_name=$fi_name1;
 
}
 
function display()
{
echo "Name of Student=". $this->fi_name."
"; echo "Roll no =". Student::ROLL; } } $s=new Student("Umar"); $s->display(); echo "
Outside the display method :"; echo "
Roll no =". Student::ROLL; ?>

Output

Name of Student=Umar
RoLL no =38
Outside the display method :
RoLL no =38

You can easily access class constant within the class and outside the class using the class name, as shown above.

Download Source Script


.

Class constant is very useful whenever you want to define fixed value throughout the class.


QUOTES OF THE DAY

To make your children capable of honesty is beginning of education.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER