passing arguments to functions in php
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?
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";
}
?>
The other one is:
<?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
<?php links( array( 'affiliate', 7 ) ); ?>
or
<?php links( array( 'social', 2 ) ); ?>
Would combining them into a reus开发者_JS百科able function save processing time/resources or would it not matter?
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";
}
}
It would not save any computer time, what it saves is your time, by not having to maintain code twice. (But watch out that converting it into a function does not cause you to spend more effort than just having it twice.)
Also, I see no reason to pass the word 'social' to the function - it's never actually used anywhere.
精彩评论