constants

Constant values can be defined within a class using the keyword const.

 

Syntax:

const myConstant = "Constant Value";

 

  • Remain the same and unchangeable
  • Do not use the $ symbol
  • Must be a constant expression
    • not a class's property, result of a mathematical operation or a function call

Example showing a const being defined within the class, then being called from within the class and again externally:

<?php
	class MyClass
	{
		const myConstant = 'constant value';

		public function showConstant() {
			echo  self::myConstant . "<br>";
		}

		public function __construct(){
			echo "Constructor: " . self::myConstant . "<br>";
		}
	}

	$test = new MyClass ;

	$test->showConstant();
?>

Save & refresh browser:

Constructor: constant value
constant value

Leave a Reply