If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
PHP में Class में Constants, वो variables होते हैं जिनकी value immutable होते हैं , means हम script के execution के समय इनकी value को change नहीं कर सकते हैं ।
किसी Class में Constants define करने के लिए const
keyword का use किया जाता है। ध्यान रहे constant को define करते समय $ sign
का use नहीं किया जाता है।
<?php
class Person
{
const SayMyName = 'Babu Rao';
}
?>
class constants को आप class object
बनाकर या direct class name के साथ ::
का use करके as a static member की तरह access कर सकते हैं।
echo Person::SayMyName . "\n"; // Babu Rao
$obj = new Person();
echo $obj::SayMyName; // Babu Rao
इसी तरह से आप class के अंदर किसी method में इन्हे self::
, static::
या $this::
की help से भी access कर सकते हैं।
<?php
class Person
{
const SayMyName = 'Babu Rao';
// Access inside a function.
public function printName() {
echo self::SayMyName ."\n";
echo $this::SayMyName ."\n";
echo static::SayMyName;
}
}
$obj = new Person();
echo $obj->printName();
?>
Output
Babu Rao Babu Rao Babu Rao
●●●
हालाँकि किसी class में defined constants की value को आप child class में change कर सकते हैं।
<?php
abstract class Person
{
const PersonName = null;
}
class User1 extends Person
{
const PersonName='Babu Rao';
}
class User2 extends Person
{
const PersonName='Shyam';
}
echo User1::PersonName. "\n";
echo User2::PersonName;
?>
Output
Babu Rao Shyam
लेकिन अगर आप चाहते हैं कि constants की value किसी sub class में भी change न हो तो इसे आप final define कर सकते हैं।
<?php
abstract class Person
{
// Now declare it as final.
final const PersonName = null;
}
class User1 extends Person
{
const PersonName='Babu Rao';
}
?>
Output
PHP Fatal error: User1::PersonName cannot override final constant Person::PersonName
●●●
I Hope , अब आप PHP में Class constants के बारे में अच्छे से समझ गए होंगे।
Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)
Get connected with me. :) LinkedIn Twitter Instagram Facebook