除了一些小的变量命名差异外,我还有一些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 ) ); ?>
将它们组合成一个可重用的函数会节省处理时间/资源,还是无关紧要?
发布于 2011-09-14 08:29:52
唯一真正改变的是类别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";
}
}发布于 2011-09-14 08:29:15
它不会节省任何计算机时间,它节省的是您的时间,通过不必维护代码两次。(但要注意,将其转换为函数并不会使您花费更多的精力,而不是只花两次。)
而且,我认为没有理由把'social‘这个词传递给这个函数--它从来没有在任何地方使用过。
https://stackoverflow.com/questions/7413319
复制相似问题