Class constant in php with example in 2022

Class constant in php with example in 2021
Class constant in php with example in 2021

Class constant in php with example

Class Constant: constant is an element of class that can not be changed once it is declared. the const keyword is used to declare a constant. the constant can be accessed inside and outside a class. 

Outside a class, it can be accessed using scope resolution (::) symbol and class name. Inside a class, it can be accessed using self keyword and scope resolution (::) symbol.

Java Language

Accessing const outside a class: it is recommended to name the constants in all uppercase letters but it is not compulsory.

Python Language

How to use Accessing const outside a class in PHP?

<?php

class Student 

{

  const NAME= "Icoderweb";

  const ROLLNO=2021;

}

echo "Student Name:".Student::NAME."<br>";

echo "Student Rollno:".Student::ROLLNO."<br>";

?>

*****OUTPUT*****

Student Name:Icoderweb

Student Rollno:2021


Accessing const inside a class: const data can be accessed inside a class using self keyword and class name.

How to use Accessing const inside a class in php.

class Student 

{

  const NAME= "Icoderweb";

  const ROLLNO=2021;

  function intro()

  {

  echo "Student Name:".self::NAME."<br>";

  echo "Student Rollno:".self::ROLLNO."<br>";

  echo "Student Name:".Student::NAME."<br>";

  echo "Student Rollno:".Student::ROLLNO."<br>";

  }

}

$obj=new Student();

$obj->intro();

?>

*****OUTPUT*****

Student Name: Icoderweb

Student Rollno:2021

Student Name: Icoderweb

Student Rollno:2021

Post a Comment

0 Comments