5

I have a PHP class with a bunch of methods. Currently they are in no particular order. I would (at least initially) like them to be in alphabetical order, so public function a() would come before public function b() and so on.

I'm sure I could write a script to do this but is there an existing program that can do it for me? All I can find is ways to sort individual lines.

user2864740
  • 60,010
  • 15
  • 145
  • 220
jxmallett
  • 4,087
  • 1
  • 28
  • 35
  • 2
    Do you use any special IDE? E.g. Eclispe can sort methods. – MrTux Sep 24 '14 at 23:02
  • 1
    http://stackoverflow.com/questions/19119697/sublime-text-2-plugin-to-sort-your-functions-alphabetically might help you – royhowie Sep 24 '14 at 23:04
  • Write all functions inline. then copy and paste into a spreadsheet. Sort and paste back to the .php file – zkanoca Sep 24 '14 at 23:04
  • Sorting alphabetically .. uhg. Isn't this request simply born by not using an IDE with good navigation? I recommend ordering by logical task/group. Anyway, the larger task is marginally interesting: "how to sort paragraphs of text", where the first step becomes how to identity the "paragraphs". – user2864740 Sep 24 '14 at 23:22
  • Thanks guys. I agree the situation is far from ideal and that methods should be grouped by what they do. Time to ditch my fancy notepad and find a real IDE. – jxmallett Sep 25 '14 at 00:36
  • OMG why did I not do this sooner? Having fun with PhpStorm. – jxmallett Sep 25 '14 at 02:29
  • 1
    @jxmallett Yeah, it's a great IDE. Well worth the money. – GolezTrol Sep 25 '14 at 07:17

2 Answers2

3

Various IDEs can do this for you. Apparently Eclipse can, I know PHPStorm can and Netbeans can probably do it as well.

But I would not do this. It's not needed. A proper IDE should be able to display a list of methods in any order you like, and let you jump to them.

Moreover, if you want to rename a method, you would also have to move it. If you commit the changes to version control, it looks like the whole method was removed while another was inserted. This really messes up your history and makes it hard to review changes.

We had alphabetical order as a coding style guideline before, but dropped it (fortunately) for this very reason.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
1

You might find the documentation of Reflection useful, here's an example:

$reflector = new ReflectionClass('example');
$methods = $reflector->getMethods();
usort($methods, function($method1, $method2) {
    return strcasecmp($method1->getName(), $method2->getName());
});

However I would not recommend you to do that since it is better to order your methods according to what they do, for you or any other programmer that is likely to read your code.

What you want to do is work with an IDE that can change the view without modifying the source code. Many IDEs can do that including Netbeans and Eclipse.

Adam Sinclair
  • 1,654
  • 12
  • 15