向函数传递参数在PHP [英] passing arguments to functions in php

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

问题描述

我有一些PHP code是pretty多被复制保存一些小的变量命名的差异。我怎样才能变成一个可重用的功能,我可以传递参数通过这个?

I have some php code that is pretty much being duplicated save for some minor variable naming differences. How can I turn this into a reusable function where I can pass arguments thru?

这是code,我现在用的两倍。第二个是除外附属机构的所有引用相同更改为社会人。

This is the code which I am using twice. The second one is the same except all references of "affiliate" is changed to "social".

<?php
    $affiliate = wp_list_bookmarks( array( 'categorize' => 0, 'category' => '7', 'title_li' => '', 'orderby' => 'rating', 'show_images' => 0, 'echo' => 0 ) );
    preg_match_all( '/<li>.*?<\/li>/', $affiliate, $affiliate_matches );
    foreach ( $affiliate_matches[0] as $affiliate_match ) {
        preg_match( '/title=".*?"/', $affiliate_match, $affiliate_title );
        echo str_replace(
            $affiliate_title[0],
            $affiliate_title[0] . ' ' . strtolower( str_replace( array( 'title="', ' ' ), array( 'class="', '-' ), $affiliate_title[0] ) ),
            $affiliate_match
        ) . "\n";
    }
?>

另一种是:

<?php
    $social = wp_list_bookmarks( array( 'categorize' => 0, 'category' => '2', 'title_li' => '', 'orderby' => 'rating', 'show_images' => 0, 'echo' => 0 ) );
    preg_match_all( '/<li>.*?<\/li>/', $social, $social_matches );
    foreach ( $social_matches[0] as $social_match ) {
        preg_match( '/title=".*?"/', $social_match, $social_title );
        echo str_replace(
            $social_title[0],
            $social_title[0] . ' ' . strtolower( str_replace( array( 'title="', ' ' ), array( 'class="', '-' ), $social_title[0] ) ),
            $social_match
        ) . "\n";
    }
?>

我想也许我可以调用像

I was thinking maybe I can call the function like

&LT; PHP的链接(阵列('子公司',7)); ?&GT;

&LT; PHP的链接(阵列(社会,2)); ?&GT;

他们会结合成一个可重用的功能,节省处理时间/资源,或将它不要紧?

Would combining them into a reusable function save processing time/resources or would it not matter?

推荐答案

这是真正改变的是类别ID,所以你只需要这个传递给函数的唯一的事。

the only thing that really changes is the category id so you only need to pass this to the function.

function links($categoryId) {
        $affiliate = wp_list_bookmarks( array( 'categorize' => 0, 'category' => $categoryId, 'title_li' => '', 'orderby' => 'rating', 'show_images' => 0, 'echo' => 0 ) );
        preg_match_all( '/<li>.*?<\/li>/', $affiliate, $affiliate_matches );
        foreach ( $affiliate_matches[0] as $affiliate_match ) {
            preg_match( '/title=".*?"/', $affiliate_match, $affiliate_title );
            echo str_replace(
                $affiliate_title[0],
                $affiliate_title[0] . ' ' . strtolower( str_replace( array( 'title="', ' ' ), array( 'class="', '-' ), $affiliate_title[0] ) ),
                $affiliate_match
            ) . "\n";
        }

    }

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

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