有人可以帮我简化这段代码吗?有没有办法可以永久地将$ the_campus传递给is_campus()而不使用全局范围? $ the_campus从数据库中提取并且值发生变化,但变量总是被称为$ the_campus。
谢谢!
$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'); ?>
答案 0 :(得分:5)
您可能会设计一种传递变量的方法,而无需在函数中明确写出global
,但请不要。功能很好,因为它是;引入与变量的“不可见”耦合会使你的代码更糟,而不是更好。
可能想要做的是重构代码,使其以相同的方式工作,但使用起来更简单,例如:
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', '...', '...')); ?>
答案 1 :(得分:0)
虽然我最终不会推荐这个:
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';
}
}
}
尽早打电话到这个地方:
$helper = new CCampushelper();
$helper->bindVariable( $campuses );
后来就此:
<?php $helper->is_campus( 'university-of-minnesota-tc' ); ?>
<?php $helper->is_campus( 'university-of-wisconsin' ); ?>
<?php $helper->is_campus( 'university-of-chicago' ); ?>