PHP code example of tomwright / currency-php

1. Go to this page and download the library: Download tomwright/currency-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tomwright / currency-php example snippets



$rateFetcher = new MyConversionRateFetcher();
$factory = new CurrencyFactory($rateFetcher);

$gbp = $factory->create('GBP');
$usd = $factory->create('USD');

$priceInGBP = 100;
$priceInUSD = $gbp->convertTo($usd, $priceInGBP);
echo $priceInUSD; // 126

class FixedRateFetcher implements ConversionRateFetcherInterface
{

    /**
     * @param Currency $from
     * @param Currency $to
     * @return float
     */
    public function getConversionRate(Currency $from, Currency $to)
    {
        $rates = [
            [
                'from' => 'GBP',
                'to' => 'USD',
                'rate' => 1.2547,
            ],
            [
                'from' => 'USD',
                'to' => 'GBP',
                'rate' => 0.7974,
            ],
            [
                'from' => 'GBP',
                'to' => 'CAD',
                'rate' => 1.6612,
            ],
            [
                'from' => 'CAD',
                'to' => 'USD',
                'rate' => 0.7539,
            ],
        ];

        $result = null;

        foreach ($rates as $rate) {
            if ($rate['from'] === $from->getCurrencyCode() && $rate['to'] === $to->getCurrencyCode()) {
                $result = $rate['rate'];
            }
        }
        return $result;
    }
}

composer install tomwright/currency-php