PHP Constant

PHP Constant

Last Updated on Mar 22, 2023

What is a constant?

Constants are like variables that can’t be changed. Hence the name! it’s constant and it’s not variable.

You can define a constant by using the keyword const and you don’t need the dollar sign ($) in your name and even when you want to use it you don’t need the $

we normally write the name of the constant all uppercase

const NAME= 'amir';
echo NAME;
// amir

After you define the constant if you try to change it you’ll get an error

const NAME= 'amir';
NAME= 'pratham';
// error

You can also have constants inside your class

class Example{
    const MESSAGE = 'I am a constant inside a class';
}

Constants inside the class act like static parameters.

inside the class we get access to them with self and outside the class we access them with ::

class Example{
    const MESSAGE = 'I am a constant inside a class';
    public function getMesasge(){
        echo self::MESSAGE;
    }
}
https://youtu.be/YEm7NvXxFUo

Conclusion

Now you know about constants in PHP.

I recommend you to open a PHP files and define multiple constants. compare them to variables.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • what are constants
  • how to define a constant
  • how to use constants
  • constant in class

Category: programming

Tags: #php #oop

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses