Playing around with strings
| From: | Robin Vickery | Date: | Thu, 20 Mar 2008 13:57:13 +0000 |
| Subject: | Playing around with strings | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-271886@lists.php.net to get a copy of this message | ||
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";
?>