I’m just going to leave this nifty little PHP snippet here, and recommend against it’s use. It could very well be shorter and more concise, probably a bit more performant too, but it works:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Example { | |
public function length(){ | |
return 5; | |
} | |
public function __call($name,$arguments){ | |
$methods = get_class_methods($this); | |
$ldist = 9999; | |
$currmethod = $name; | |
foreach($methods as $m){ | |
$distance = levenshtein($name,$m); | |
if($distance < $ldist){ | |
$currmethod = $m; | |
$ldist = $distance; | |
} | |
} | |
return call_user_func(array($this,$currmethod),$arguments); | |
} | |
} | |
$example = new Example(); | |
echo $example->elngth(); |
It also encourages bad practices and ambiguity ( should elngth be mapped on to length1 or length2? If you’re willing to run levenshtein in your head, maybe you should spell correctly ).
Inspired by this tweet:
>>> def method_missing(n, *a, &b); send(methods.min_by { |m| levenshtein(n.to_s, m.to_s) }, *a, &b); end
>> p [1, 2, 3].elngth
3It's fine.
— Gary Bernhardt (@garybernhardt) October 10, 2012
@garybernhardt and in PHP, http://t.co/JGeCpbfP You have been mentioned!
RT @Tarendai New Blogpost: PHP Missing Methods & Levenshtein Distance http://t.co/A0HId4s7 #wordpress
RT @Tarendai: New Blogpost: PHP Missing Methods & Levenshtein Distance http://t.co/NKhgpmER #wordpress
RT @Rarst RT @Tarendai: New Blogpost: PHP Missing Methods & Levenshtein Distance http://t.co/A0HId4s7 #wordpress
@Tarendai Neat!