PHP Class Constants

PHP

PHP Class Constants

एक बार घोषित होने के बाद Constants कभी नहीं बदले जा सकते। Class constant हमेसा case-sensitive होता है। हालाँकि, constants के नाम को uppercase में लिखना recommend की जाती है।

  • PHP Class Constants घोषित करने के लिए const कीवर्ड का उपयोग किया जाता है।
  • Constant नॉर्मल वेरिएबल से भिन्न होते हैं इसलिए Constant नाम से पहले कोई $ (dollar sign) की आवश्यकता नहीं है, जिसे PHP Constants चैप्टर में भी देख चुके हैं।
  • एक class constant, const कीवर्ड की मदद से किसी क्लास के अंदर घोषित किया जाता है।

Class constant को दो तरीको से एक्सेस किया जा सकता हैं:

  • Inside the Class
  • Outside the Class

Inside the Class

हम self कीवर्ड का उपयोग करके क्लास के अंदर से constant को एक्सेस कर सकते हैं, scope resolution operator (::) के बाद constant का नाम इस्तेमाल कर के, जैसे निचे उदहारण में देख सकते है।

उदाहरण: PHP Class Constant inside class
<?php
class Planet{
    const SUNRISE = "Sun rises in the east!";
    public function morning(){
        echo self::SUNRISE;
        // self कीवर्ड का उपयोग
    }
}

$planet = new Planet();
$planet->morning();

// Result: Sun rises in the east!
?>

Outside the Class

हम क्लास के बाहर से constant को एक्सेस कर सकते हैं, सबसे पहले क्लास के नाम उसके बाद scope resolution operator (::) और उसके बाद सबसे आखिरी में constant का नाम इस्तेमाल कर के, जैसे निचे उदहारण में देख सकते है।

उदाहरण: PHP Class Constant outside class
<?php
class Planet{
    const SUNRISE = "Sun rises in the east!";
}
echo Planet::SUNRISE;

// Result: Sun rises in the east!
?>
Article By: Brajlal Prasad
Created on: 10 Jun 2023  686  Views
 Print Article
Report Error

If you want to report an error, or any suggestion please send us an email to [email protected]