## 7.16.1. ProblemYou want to define constants on a per-class basis, not on a global basis. ## 7.16.2. SolutionDefine them like class properties, but use the class Math { const pi = 3.14159; // universal const e = 2.71828; // constants } $area = math::pi * $radius * $radius; ## 7.16.3. DiscussionPHP reuses its concept of global constants and applies them to classes. Essentially, these are final properties. Declare them using the class Math { const pi = 3.14159; // universal const e = 2.71828; // constants } $area = math::pi * $radius * $radius; Like static properties, you can access constants without first instantiating a new instance of your class, and they're accessed using the double colon ( Unlike properties, constants do not have a dollar sign ( class Circle { const pi = 3.14159; protected $radius; public function __construct($radius) { $this->radius = $radius; } public function circumference() { return 2 * self::pi * $this->radius; } } $c = new circle(1); print $c->circumference(); 6.28318 This example creates a circle with a radius of define('pi', 10); // global pi constant class Circle { const pi = 3.14159; // class pi constant protected $radius; public function __construct($radius) { $this->radius = $radius; } public function circumference() { return 2 * pi * $this->radius; } } $c = new circle(1); print $c->circumference(); 20 Oops! PHP has used the value of Although it's unlikely that you will accidentally redefine Π (you'll probably use the built-in You cannot assign the value of an expression to a constant, nor can they use information passed into your script: // invalid class permissions { const read = 1 << 2; const write = 1 << 1; const execute = 1 << 0; } // invalid and insecure class database { const debug = $_REQUEST['debug']; } Neither the constants in Since you need to access constants using an explicit name, either class Constants { const pi = 3.14159; // rest of class here } $class = 'Constants'; print $class::pi; This produces a parse error, even though this type of construct is legal for non-constant expressions, such as ## 7.16.4. See AlsoDocumentation on class constants is available at http://www.php.net/manual/en/language.oop5.constants.php. |

PHP Cookbook: Solutions and Examples for PHP Programmers

ISBN: 0596101015

EAN: 2147483647

EAN: 2147483647

Year: 2006

Pages: 445

Pages: 445

Authors: Adam Trachtenberg, David Sklar

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net