note 108717 added to language.constants

From: Date: Sun, 20 May 2012 03:04:11 +0000
Subject: note 108717 added to language.constants
Groups: php.notes 
Request: Send a blank email to php-notes+get-188090@lists.php.net to get a copy of this message
CONSTANTS and PHP Class Definitions Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, or string (no array or other object types) -- right away. <?php define('MIN_VALUE', '0.0'); // RIGHT - Works OUTSIDE of a class definition. define('MAX_VALUE', '1.0'); // RIGHT - Works OUTSIDE of a class definition. //const MIN_VALUE = 0.0; WRONG - Works INSIDE of a class definition. //const MAX_VALUE = 1.0; WRONG - Works INSIDE of a class definition. class Constants { //define('MIN_VALUE', '0.0'); WRONG - Works OUTSIDE of a class definition. //define('MAX_VALUE', '1.0'); WRONG - Works OUTSIDE of a class definition. const MIN_VALUE = 0.0; // RIGHT - Works INSIDE of a class definition. const MAX_VALUE = 1.0; // RIGHT - Works INSIDE of a class definition. public static function getMinValue() { return self::MIN_VALUE; } public static function getMaxValue() { return self::MAX_VALUE; } } ?> #Example 1: You can access these constants DIRECTLY like so: * type the class name exactly. * type two (2) colons. * type the const name exactly. #Example 2: Because our class definition provides two (2) static functions, you can also access them like so: * type the class name exactly. * type two (2) colons. * type the function name exactly (with the parentheses). <?php #Example 1: $min = Constants::MIN_VALUE; $max = Constants::MAX_VALUE; #Example 2: $min = Constants::getMinValue(); $max = Constants::getMaxValue(); ?> Once class constants are declared AND initialized, they cannot be set to different values -- that is why there are no setMinValue() and setMaxValue() functions in the class definition -- which means they are READ-ONLY and STATIC (shared by all instances of the class). ---- Server IP: 69.147.83.197 Probable Submitter: 69.19.176.2 ---- Manual Page -- http://www.php.net/manual/en/language.constants.php Edit -- https://master.php.net/note/edit/108717 Del: integrated -- https://master.php.net/note/delete/108717/integrated Del: useless -- https://master.php.net/note/delete/108717/useless Del: bad code -- https://master.php.net/note/delete/108717/bad+code Del: spam -- https://master.php.net/note/delete/108717/spam Del: non-english -- https://master.php.net/note/delete/108717/non-english Del: in docs -- https://master.php.net/note/delete/108717/in+docs Del: other reasons-- https://master.php.net/note/delete/108717 Reject -- https://master.php.net/note/reject/108717 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188090) next »