Reputation: 666
Can someone help me simplify this code? Is there a way I can permanently pass $the_campus to is_campus() without using a global scope? $the_campus is pulling from a database and the value changes, but the variable is always called $the_campus.
Thanks!
$the_campus = $search_term['campus'];
function is_campus($the_campus, $selected_campus) {
if ( $selected_campus == $the_campus ) {
echo 'selected';
}
}
<?php is_campus($the_campus, 'university-of-minnesota-tc'); ?>
<?php is_campus($the_campus, 'university-of-wisconsin'); ?>
<?php is_campus($the_campus, 'university-of-chicago'); ?>
Upvotes: 0
Views: 66
Reputation: 11999
While I won't ultimately recommend this:
class CCampushelper {
// will be found by reference
protected $campus;
public
function bindVariable( &$externalCampus ) {
$this->campus =& $externalCampus;
}
public
function is_campus( $selected_campus) {
if ( $selected_campus === $this->campus ) {
echo 'selected';
}
}
}
Call this somewhere early:
$helper = new CCampushelper();
$helper->bindVariable( $campuses );
And later on this:
<?php $helper->is_campus( 'university-of-minnesota-tc' ); ?>
<?php $helper->is_campus( 'university-of-wisconsin' ); ?>
<?php $helper->is_campus( 'university-of-chicago' ); ?>
Upvotes: 0
Reputation: 437424
You might devise a way of passing the variable without explicitly writing global
in your function, but please do not. The function is just fine as it is; introducing "invisible" coupling with a variable is going to make your code worse, not better.
What you would probably want to do is refactor the code so that it works in an equivalent manner but is more straightforward to use, for example:
function echo_campus_string($the_campus, array $campuses) {
foreach($campuses as $campus) {
if($campus == $the_campus) {
echo 'selected'; // you will probably want to make the output more involved
// perhaps break as well?
}
}
}
<?php echo_campus_string($the_campus, array('university-of-minnesota-tc', '...', '...')); ?>
Upvotes: 5