Yargicx, thanks for asking this question. It caused me to learn a new feature of PHP (5.3). Here is the code that returns the answer to your original question: formatted currency in JSON. It may look a little weird if you aren't familiar with invokable classes, but I'll explain how it works.
use Zend\I18n\View\Helper\CurrencyFormat;
use Zend\View\Model\JsonModel;
class MyController extends AbstractActionController
{
public function myAction()
{
$data = array();
//i want to format this data for multi currency format. as us,fr,tr etc..
$currencyFormatter = new CurrencyFormat();
$data['amount'] = $currencyFormatter(1234.56, "TRY", "tr_TR");
return new JsonModel($data);
}
}
To get to this point, I looked up the currencyFormat()
method in the Zend\I18n\View\Helper\CurrencyFormat
class and noticed that this was a protected method, thus I couldn't use it directly in the controller action.
I then noticed that there was a magic __invoke()
method and (having never seen this before) I looked up the PHP documentation for it at http://www.php.net/manual/en/language.oop5.magic.php#object.invoke. As it turns out, you can use an object as if it is a function like the following. Note the very last line:
class Guy
{
public function __invoke($a, $b)
{
return $a + $b;
}
}
$guy = new Guy();
$result = $guy();
Since the __invoke()
method of the Zend\I18n\View\Helper\CurrencyFormat
class returns the result of a call to the currencyFormat()
method, we can invoke the class with the same parameters as the currencyFormat()
method, resulting in the original codeblock in this answer.
For kicks, here is the source code of the __invoke()
function of the Zend\I18n\View\Helper\CurrencyFormat
class:
public function __invoke(
$number,
$currencyCode = null,
$showDecimals = null,
$locale = null,
$pattern = null
) {
if (null === $locale) {
$locale = $this->getLocale();
}
if (null === $currencyCode) {
$currencyCode = $this->getCurrencyCode();
}
if (null === $showDecimals) {
$showDecimals = $this->shouldShowDecimals();
}
if (null === $pattern) {
$pattern = $this->getCurrencyPattern();
}
return $this->formatCurrency($number, $currencyCode, $showDecimals, $locale, $pattern);
}