Using usort in php with a class private function

后端 未结 5 996
闹比i
闹比i 2020-12-02 07:10

ok using usort with a function is not so complicated

This is what i had before in my linear code

function merchantSort($a,$b){
    return ....// stuf         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 08:10

    You need to pass $this e.g.: usort( $myArray, array( $this, 'mySort' ) );

    Full example:

    class SimpleClass
    {                       
        function getArray( $a ) {       
            usort( $a, array( $this, 'nameSort' ) ); // pass $this for scope
            return $a;
        }                 
    
        private function nameSort( $a, $b )
        {
            return strcmp( $a, $b );
        }              
    
    }
    
    $a = ['c','a','b']; 
    $sc = new SimpleClass();
    print_r( $sc->getArray( $a ) );
    

提交回复
热议问题