PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

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;

Run Example ››

Why Class Constants?

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

Did you know? There's a #Group for you to get help on PHP.
Profile Picture
Supun Kavinda
I'm the Founder of Hyvor, Web Developer, Physics Lover, Flutist, and a Table Tennis Player.
My Websites