[英]passing arguments to functions in php
我有一些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 ) ); ?>
将它们组合成可重用的功能可以节省处理时间/资源,还是没关系?
它不必节省任何计算机时间,而不必两次维护代码,可以节省您的时间。 (但是请注意,将其转换为函数并不会使您付出更多的努力,而不仅仅是两次。)
另外,我认为没有理由将“社交”一词传递给该函数-从未在任何地方实际使用过。
唯一真正更改的是类别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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.