On 20/03/2008, Robin Vickery <[EMAIL PROTECTED]> wrote:
> Hiyah,
>
>  Here's a trick you can use to evaluate expressions within strings. It
>  may not be particularly useful, but I thought it was interesting.
>
>  It exploits two things:
>
>  1. If you interpolate an array element within a string, the index of
>  the element is evaluated as a php expression.
>
>  2. You can can make your own magic arrays by extending arrayObject.
>
>
>  <?php
>  class identityArrayObject extends arrayObject
>  {
>   public function offsetGet($index)
>   {
>     return $index;
>   }
>  }
>
>  $eval = new identityArrayObject;
>
>  print "The square root of {$eval[pow(2,2)]} is {$eval[sqrt(4)]} \n";
>
>  print "Price: $price GBP ({$eval[$price * 1.175]} GBP including tax) \n";
>
>  ?>
>
>  You can extend it to add your own formatting elements:
>
>  <?php
>  class uppercaseArrayObject extends arrayObject
>  {
>   public function offsetGet($index)
>   {
>     return strtoupper($index);
>   }
>  }
>
>  $U = new uppercaseArrayObject;
>  $city = 'edinburgh';
>
>  print "The capital of Scotland is $U[$city] \n";
>  ?>
>

More generic:

<?php

class transformArrayObject extends arrayObject
{
  protected $transform;

  public function __construct($transform = null)
  {
    $this->transform = is_null($transform) ? array($this, 'identity')
: $transform;
  }

  public function offsetGet($index)
  {
    return call_user_func($this->transform, $index);
  }

  public function identity($index)
  {
    return $index;
  }
}

$eval = new transformArrayObject;
$U    = new transformArrayObject('strtoupper');
$u    = new transformArrayObject('ucfirst');
$L    = new transformArrayObject('strtolower');
$GBP  = new transformArrayObject(create_function('$index', 'return
money_format("%n", $index);'));

$price = 50;
$tax = 1.175;
$city = 'EdInBurGH';

print "A ticket to $U[$city] is: $GBP[$price] ({$GBP[$price * $tax]}
including VAT)\n";
// A ticket to EDINBURGH is: £50.00 (£58.75 including VAT)

?>

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to