Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function config_parser()
- {
- // Do some code here
- // $hash_method is in config_parser() local scope
- $hash_method = 'multiply';
- if ($hashing_enabled)
- {
- function do_hash_method($var)
- {
- // $hash_method is from the parent's local scope
- if ($hash_method == 'multiply')
- return $var * $var;
- else
- return $var ^ $var;
- }
- }
- }
- function hashme($val)
- {
- // do_hash_method still knows about $hash_method
- // even though it's not in the local scope anymore
- $val = do_hash_method($val)
- }
- function replace_spaces ($text) {
- $replacement = function ($matches) {
- return str_replace ($matches[1], ' ', ' ').' ';
- };
- return preg_replace_callback ('/( +) /', $replacement, $text);
- }
- class ConfigurableEncoder{
- private $algorithm = 'multiply'; //default is multiply
- public function encode($x){
- return call_user_func(array($this,$this->algorithm),$x);
- }
- public function multiply($x){
- return $x * 5;
- }
- public function add($x){
- return $x + 5;
- }
- public function setAlgorithm($algName){
- switch(strtolower($algName)){
- case 'add':
- $this->algorithm = 'add';
- break;
- case 'multiply': //fall through
- default: //default is multiply
- $this->algorithm = 'multiply';
- break;
- }
- }
- }
- $raw = 5;
- $encoder = new ConfigurableEncoder(); // set to multiply
- echo "raw: $rawn"; // 5
- echo "multiply: " . $encoder->encode($raw) . "n"; // 25
- $encoder->setAlgorithm('add');
- echo "add: " . $encoder->encode($raw) . "n"; // 10
Add Comment
Please, Sign In to add comment