参数传递给函数在PHP(passing arguments to functions in php)

2019-10-30 03:58发布

我有一个几乎被复制保存一些小的变量命名的差别一些PHP代码。 我怎样才能变成一个可重复使用的功能,我可以传递参数通过这个?

这是我使用两倍的代码。 第二个是除的“关联方”的所有引用相同更改为“社会人”。

<?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";
    }
?>

我想也许我可以调用的功能等

<?php links( array( 'affiliate', 7 ) ); ?>

要么

<?php links( array( 'social', 2 ) ); ?>


将它们合并为一个可重复使用的功能,节省处理时间/资源或将它不要紧?

Answer 1:

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

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";
        }

    }


Answer 2:

它不会保存任何计算机时,它可以节省您的时间,由于无需维护的代码的两倍。 (但是要注意的是,将其转换成一个函数不会导致你花费更多的力气比仅仅有两次。)

另外,我认为没有理由词“社会”传递给函数 - 它实际上从未在任何地方使用。



文章来源: passing arguments to functions in php