Hoofdstuk 21. Zend_Measure

Inhoudsopgave

21.1. Introduction
21.2. Creation of Measurements
21.2.1. Creating measurements from integers and floats
21.2.2. Creating measurements from strings
21.2.3. Measurements from localized strings
21.3. Outputting measurements
21.3.1. Automatic output
21.3.2. Outputting values
21.3.3. Output with unit of measurement
21.3.4. Output as localized string
21.4. Manipulating Measurements
21.4.1. Convert
21.4.2. Add and subtract
21.4.3. Compare
21.4.4. Compare
21.4.5. Manually change values
21.4.6. Manually change types
21.5. Types of measurements
21.5.1. Hints for Zend_Measure_Binary
21.5.2. Hints for Zend_Measure_Number
21.5.3. Roman numbers

21.1. Introduction

Zend_Measure_* classes provide a generic and easy way for working with measurements. Using Zend_Measure_* classes, you can convert measurements into different units of the same type. They can be added, subtracted and compared against each other. From a given input made in the user's native language, the unit of measurement can be automatically extracted. Numerous units of measurement are supported.

Voorbeeld 21.1. Converting measurements

The following introductory example shows automatic conversion of units of measurement. To convert a measurement, its value and its type have to be known. The value can be an integer, a float, or even a string containing a number. Conversions are only possible for units of the same type (mass, area, temperature, velocity, etc.), not between types.

<?php
require_once 'Zend/Measure/Length.php';

$locale = new Zend_Locale('en');
$unit = new Zend_Measure_Length(100, Zend_Measure_Length::METER, $locale);

// Convert meters to yards
echo $unit->convertTo(Zend_Measure_Length::YARD);
?>

Zend_Measure_* includes support for many different units of measurement. The units of measurement all have a unified notation: Zend_Measure_<TYPE>::NAME_OF_UNIT, where <TYPE> corresponds to a well-known physical or numerical property. . Every unit of measurement consists of a conversion factor and a display unit. A detailed list can be found in the chapter Types of measurements .

Voorbeeld 21.2. The meter measurement

The meter is used for measuring lengths, so its type constant can be found in the Length class. To refer to this unit of measurement, the notation Length::METER must be used. The display unit is m.

<?php
require_once 'Zend/Measure/Length.php';

echo Zend_Measure_Length::STANDARD;  // outputs 'Length::METER'
echo Zend_Measure_Length::KILOMETER; // outputs 'Length::KILOMETER'

$unit = new Zend_Measure_Length(100,'METER');
echo $unit;
// outputs '100 m'
?>