happy cat image

everdevel

coding

login
NotificationX
  • Currently, only notices of comments are displayed.
  • no comment or please login

Constants in Class

I can declare constants that are used in that class.
To declare a constant, use the const keyword. Constants are declared in uppercase letters. Of course it's a promise.

How to declare a constant in a class

  1. const constant name = value;

How constants are used in class

  1. self::constant name;

So let's declare and use a constant

  1. <?php
  2. class Car
  3. {
  4. const TRUNK = true;
  5.  
  6. public function checkTrunk()
  7. {
  8. return self::TRUNK;
  9. }
  10. }
  11.  
  12. $car = new Car;
  13. if($car->checkTrunk() == true){
  14. echo "This car has a trunk." ;
  15. } else {
  16. echo "This car has no trunk." ;
  17. }
  18. ?>

Result

To use a constant from a class outside the class, use instance ::.

How To Use constant in class

  1. Instance :: constant name;
  1. <?php
  2. class Car
  3. {
  4. const TRUNK = true;
  5.  
  6. public function checkTrunk()
  7. {
  8. return self::TRUNK;
  9. }
  10. }
  11.  
  12. $car = new Car;
  13. if($car::TRUNK == true){
  14. echo "This car has a trunk.";
  15. } else {
  16. echo "This car has no trunk.";
  17. }
  18. ?>

Of course, you must declare an instance so that you can use class constants outside the class.


Thank you for visiting. If you have any inquiry or explanation of mistakes, please use the comments below.

הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Back to the course

ALL COMMENTS 0

Sort by