Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Sep 23 Previous

Item 547234

Consider this useless program:

<?php

class ToggleSwitch {
        const TOGGLE_STATES = array("on" => true, "off" => false);
        public $state = false;
        function __construct() {
                $this->state = rand(0, 1) ? true : false;
        }
}

$switch = new ToggleSwitch();

if ($switch->state === ToggleSwitch::TOGGLE_STATES["on"]) {
        echo "School's in";
} else {
        echo "School's out";
}

?>

What will it display in your browser?

A: "School's in"
B: "School's out"
C: "School's in" or "School's out" with an equal probability interval
D: Fatal Error

Answer

There are three sorts of constants in PHP: constants created with define(), class constants or constants created with the keyword const and magic constants. A constant is some kind of identifier for a constant value. Much like a variable it is assigned a value, but in contrast to a variable its value cannot be changed after assignment. This is a very simple concept but I can't stress its importance enough: constants are extremely reliable and have global scope too.

There are some limitations as well: magic constants are assigned a value by PHP so you can only read out their values. The constants created with define() are the most flexible: they are created at the time define() was called and despite the fact that they are limited to scalar values they can contain computed values.

Class or constants created with the const keyword are limited to scalar values as well but their value is also assigned at compile time and not at run time. Here are some examples to illustrate this:

define("D_INT", 6);
const C_INT = 6;

define("D_STR", "Hell raiser"); const C_STR = "Hell raiser";

define("D_START_TIME", microtime(true)); //const D_START_TIME = microtime(true);

//define("D_ARRAY", array("Geen donder", "geen klote", "geen reet")); //const C_ARRAY = array("Geen donder", "geen klote", "geen reet");

define("D_ARRAY2", serialize(array("Geen donder", "geen klote", "geen reet"))); //const C_ARRAY2 = serialize(array("Geen donder", "geen klote", "geen reet"));

[/code]

To make a long story short: the useless program ends with a fatal error.