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

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

问题描述

我有以下功能.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.

但我不明白如何将 extra 参数传递给 usort 回调.尝试做一个JS风格的匿名函数,但是服务器上的PHP版本太旧,抛出了语法错误.

But I don't understand 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); 
} 

推荐答案

在 PHP 中,callback 是传递一个包含对象句柄和方法名称的二元素数组来调用该对象.例如,如果$objMyCallable 类的一个实例,并且您想调用MyCallablemethod1 方法> 在 $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);
    }
}

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

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