传递额外的参数usort回调 [英] Pass extra parameters to usort callback

查看:177
本文介绍了传递额外的参数usort回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能。 Wordpress的功能,但这真的是一个PHP的问题。它们根据每个对象的元数据中的 artist_lastname 属性对我的 $ term 对象进行排序。

I have the following functions. Wordpress functions, but this is really a PHP question. They sort my $term objects according to the artist_lastname property in each object's metadata.

我想在第一个函数中将一个字符串传递给 $ meta 。这将允许我重用这个代码,因为我可以将它应用到各种元数据属性。

I want to pass a string into $meta in the first function. This would let me reuse this code as I could apply it to various metadata properties.

但我不知道如何可以传递额外参数到usort回调。我试图做一个JS风格的匿名函数,但服务器上的PHP版本太旧,并引发了语法错误。

But I don't undertstand how I can pass extra parameters to the usort callback. I tried to make a JS style anonymous function but the PHP version on the server is too old and threw a syntax error.

任何帮助 - 或向右角的手册 - 感谢感谢。感谢!

Any help - or a shove towards the right corner of the manual - gratefully appreciated. Thanks!

function sort_by_term_meta($terms, $meta) 
{
  usort($terms,"term_meta_cmp");
}

function term_meta_cmp( $a, $b ) 
{
    $name_a = get_term_meta($a->term_id, 'artist_lastname', true);
    $name_b = get_term_meta($b->term_id, 'artist_lastname', true);
    return strcmp($name_a, $name_b); 
} 


推荐答案

回调是要传递包含以下内容的两元素数组:对象句柄和对对象调用的方法名。例如,如果 $ obj 是类 MyCallable 的实例,并且您要调用 method1 方法 MyCallable $ obj ,那么您可以传递 array($ obj,method1)作为回调。

In PHP, one option for a callback is to pass a two-element array containing an object handle and a method name to call on the object. For example, if $obj was an instance of class MyCallable, and you want to call the method1 method of MyCallable on $obj, then you can pass array($obj, "method1") as a callback.

一个使用这种支持的回调类型的解决方案是,使用类基本上像一个闭包类型:

One solution using this supported callback type is to define a single-use class that essentially acts like a closure type:

function sort_by_term_meta( $terms, $meta ) 
{
    usort($terms, array(new TermMetaCmpClosure($meta), "call"));
}

function term_meta_cmp( $a, $b, $meta )
{
    $name_a = get_term_meta($a->term_id, $meta, true);
    $name_b = get_term_meta($b->term_id, $meta, true);
    return strcmp($name_a, $name_b); 
} 

class TermMetaCmpClosure
{
    private $meta;

    function __construct( $meta ) {
        $this->meta = $meta;
    }

    function call( $a, $b ) {
        return term_meta_cmp($a, $b, $this->meta);
    }
}

这篇关于传递额外的参数usort回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆