I’m trying to pass variables in an include that appears on a page multiple times. While the following sample may technically work, I’m sure there is a much better way of doing this. Any help would be appreciated.
index.php
<?php $user_avatar = "user-1-avatar.jpg"; $user_username = "username-1"; $user_name = "User 1"; include '/_user-card.php'; ?> <?php $user_avatar = "user-2-avatar.jpg"; $user_username = "username-2"; $user_name = "User 2"; include '/_user-card.php'; ?>
_user-card.php
<div class="user-card"> <img src="<?php echo $user_avatar; ?>" alt=""> <p class="user-card__username"><?php echo $user_username; ?></p> <p class="user-card__name"><?php echo $user_name; ?></p> </div>
Advertisement
Answer
You can create data that you can use over and over again by using the following function.
function get_user_card($params = array()){ $output = ''; extract($params); if( isset($user_avatar) && isset($user_username) && isset($user_name) ) { ob_start(); ?> <div class="user-card"> <img src="<?php echo $user_avatar; ?>" alt=""> <p class="user-card__username"><?php echo $user_username; ?></p> <p class="user-card__name"><?php echo $user_name; ?></p> </div> <?php $output = ob_get_contents(); ob_end_clean(); } return $output; }
$user_1 = get_user_card( array( "user_avatar" => "user-1-avatar.jpg", "user_username" => "username-1", "user_name" => "User 1" ) ); echo $user_1;