douhao123457 2014-12-08 21:44
浏览 16

在usort函数中访问父类范围

Is it possible to access the parent class's methods in this scenario, using usort()?

class MyClass {    
    public function isGreater($old,$new){
        return ($new - old > 0) ? true : false;
    }

    public function load($data){
        usort($data,function($a,$b){
            return $this->isGreater($a,$b) ? 1 : -1; // THIS IS THE PROBLEM LINE
        }
    }
}

I'm assuming since usort is using its own function scope, i can't access the public method isGreater(). Is there any way to do this? I can turn that method into a static function if it helps...

  • 写回答

1条回答 默认 最新

  • 普通网友 2014-12-08 21:51
    关注

    To access variables in an outer scope in an anonymous function, you need to use the use declaration:

    public function load($data){
        $self = $this;
        usort($data,function($a,$b) use ($self){
            return $self->isGreater($a,$b) ? 1 : -1; // THIS IS THE PROBLEM LINE
        }
    }
    

    I've created a local variable $self because older versions of PHP don't allow accessing $this in a closure.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用