Class constants provide a mechanism for holding fixed values in a program. Class constants can only be defined with the const
keyword - the define
function cannot be used in this context.
Class constants may be accessed by using the double colon operator (so-called the scope resolution operator) on a class, much like static variables.
It is recommended to use uppercase letters for constants. Also note that constants are case-sensitive.
<?php
class MultiplyBy10 {
const MULT = 10;
}
echo MultiplyBy10::MULT * 2;
Or using constants inside the class:
<?php
class MultiplyBy10 {
public $num;
const MULT = 10;
function __construct($num){
$this->num = $num;
}
function __destruct() {
echo $this->num * self::MULT;
}
}
$mynum = new MultiplyBy10(5);
Exercise
Using the constant, PI = 3.14
, create a class(CircleArea
) that has radius as its property with constructor and destructor functions. Creating an instance of the class as $r
, the script should automatically display the calculated area of the circle with the radius $r
. Test your script with $r = 5
.
<?php
<?php
class CircleArea {
public $radius;
const PI = 3.14;
function __construct($radius){
$this->radius = $radius;
}
function __destruct() {
echo $this->radius * self::PI;
}
}
$r = new CircleArea(5);
{
"test_output_contains":
{
"expected":"15.7",
"error_message":"Sorry, wrong output."
},
"test_variable_exists":
[
{
"object":"$r",
"error_message":"Have you declared <code>$r<\/code>?"
},
{
"object":"$radius",
"error_message":"Have you declared <code>$radius<\/code>?"
}
],
"test_function_exists":
[
{
"object":"__construct",
"error_message":"Did you create <code>__construct<\/code>?"
},
{
"object":"__destruct",
"error_message":"Did you create <code>__destruct<\/code>?"
}
],
"success_message":"Good job!",
"error_message":"There is something wrong on your code."
}