Skip to main content

PHP OOP Class Constants

By SamK
0
0 recommends
Category(s)
Topic(s)

Class constants are helpful when you need to define fixed data that should not change within a class.

A class constant is declared inside a class using the const keyword.

Once declared, a constant's value cannot be modified.

Class constants are case-sensitive, but it's best practice to name them in uppercase letters.

To access a constant from outside the class, use the class name followed by the scope resolution operator (::) and then the constant's name, as shown in the example below.

<?php
class Welcome {
    // Declaring a class constant
    const WELCOME_MESSAGE = "Welcome to Webmastermaze.com!";
}

// Accessing the class constant from outside the class
echo Welcome::WELCOME_MESSAGE;

/*
Output:
Welcome to Webmastermaze.com!
*/
?>

We can also access a constant from within the class using the self keyword, followed by the scope resolution operator (::) and then the constant's name, as shown below:

<?php
class Welcome {
    // Declaring a class constant
    const WELCOME_MESSAGE = "Welcome to Webmastermaze.com!";

    // Accessing the constant using 'self' within the class
    public function welcome_message() {
        echo self::WELCOME_MESSAGE;
    }
}

// Creating an object of the Welcome class
$welcome = new Welcome();
$welcome->welcome_message();

/*
Output:
Welcome to Webmastermaze.com!
*/
?>

Questions & Answers