PHP OOP

PHP OOP Constants

PHP OOP Constants

Constants are pieces of information stored in the computer’s memory which cannot be changed once assigned.

Class Constants are constants that are declared within classes.

Declaring Class Constants

The const keyword is used to declare a class constant. The class constant should be declared inside the class definition. No $ (dollar sign) used.


<?php
class Welcome {
	const GREET = 'Hello World';
}

The recommendation is to name constants in all uppercase and with underscore (_) separators. Ex: CONSTANT, MY_CONSTANT.

Note that constants does not have a visibility modifier.

Accessing Class Constants

There are two ways to access class constants.

  1. Inside the class: The self keyword and Scope Resolution Operator (::) is used to access class constants from the methods in a class.
    
    public function greet() {
    	echo self::GREET;
    }
    
    
  2. Outside the class: The class name and constant name is used to access a class constant from outside a class.
    
    echo Welcome::GREET;
    
    

PHP Class Constants


<?php
class Welcome {
	const GREET = 'Hello World';
	public function greet() {
		echo self::GREET;
	}
}
$welcome = new Welcome();
$welcome -> greet();

echo "<br>";
echo Welcome::GREET;

Why Class Constants?

Class constants are useful when you need to declare some constant data (which does not change) within a class.

Leave a Reply

Your email address will not be published. Required fields are marked *

Close