php - 是否有任何工具可以在代码中按名称对 PHP 类方法进行排序?

标签 php netbeans ide coding-style

<分区>

我想知道是否有任何工具可以对 PHP 代码进行排序(准确地说是按名称对类的方法进行排序)。我用 Google 搜索了一段时间,但没有找到任何东西。

已编辑:我有很多混合的 setter 和 getter 方法,我想对它们进行排序以提高代码可读性并更容易找到它们。当然,我更喜欢将相关方法分组而不是按字母顺序对所有方法进行排序,但在每个组中我更喜欢按这种方式对它们进行排序。

最佳答案

您不想在文件本身中按字母顺序排列您的类方法。当属于一起的方法彼此靠近时,代码更容易阅读:

Concepts that are closely related should be kept vertically close to each other [G10] […] We want to avoid forcing our readers to hop around through our source files and classes

来自 Martin,Clean Code,“Vertical Distance”,pg。 80

如果您需要按字母顺序查看它们,请改用 IDE 的动态 View 。在 Netbeans 中,这称为类大纲 View 。参见 Where is the "class outline view" in Netbeans for PHP?关于如何启用它。

如果出于某种原因你非常想用 PHP 来做这件事,你可以用 Reflection API 来做。 :

// get all the methods
$reflector = new ReflectionClass('Foo');
$methods = $reflector->getMethods();

// sort methods alphabetically
usort($methods, function($method1, $method2) {
    return strcasecmp($method1->getName(), $method2->getName());
});

print_r($methods);

这会给你一个 ReflectionMethod 的数组按方法名称排序的对象。

关于php - 是否有任何工具可以在代码中按名称对 PHP 类方法进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14953833/

相关文章:

PHP 和 MySQL - 常量、函数、最佳实践?

java - 如何在 mac os mavericks 上安装 Netbeans 7.4(已经安装了 jdk 7 update 45)?

c++ - Vista 中的 C/C++ 编程

Visual Studio 2015 中的 C#、Swift 和 Android

intellij-idea - 将 IntelliJ Idea 服务器连接到 GitLab.com : what info is actually needed?

php - 如何仅删除选定的帖子?

php - 如何在 php 数组中使用 echo 以字符串形式返回

php - Symfony2 找不到 "GET/": Method Not Allowed (Allow: POST) 的路由

java - 有点混淆 SQL 和 Tomcat

java - Lookup.getDefault().lookup() 返回 null