dtf0925 2015-11-19 13:47
浏览 30
已采纳

如何将PHP回调作为非字符串传递,从而使其成为可重构的?

Introduced in PHP 5.5, it is possible to use the MyClass::class syntax to reference a class instead of passing it as 'MyClass', which is not easily refactorable as it's just a string.

I would very much like to do the same thing with the function name, when passing a callback/callable to call_user_func() or usort().

In the example

usort($files, [FileFunctions::class, 'dircmp']);

only FileFunctions can easily be refactored.

How can I reference the dircmp function in a similar way?

Using

usort($a, FileFunctions::dircmp);

leads to a Undefined class constant 'dircmp' fatal error, as the parameter after the double colons is interpreted as a constant (of course).

  • 写回答

2条回答 默认 最新

  • dpvp56187 2015-11-19 14:01
    关注
    <?php
    
    class FileFunctions {
        static function dircmp($a, $b) {
            if ($a == $b) return 0;
            return ($a > $b) ? 1:-1;
        }
    }
    
    $files = [2,6,1,6,9,2,6,1,7,4];
    
    usort($files, function($a, $b) {return FileFunctions::dircmp($a, $b);});
    var_dump($files);
    

    PHPStorm10 correctly refactored dircmp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程