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";
?>

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

Reply via email to