我有一个带有一堆静态变量的类,比如
class staticVars{
public static $host1 = 'www.host1.com';
public static $host2 = 'www.host2.com';
public static $host3 = 'www.host3.com';
public static $host4 = 'www.host4.com';
...
}
我正在访问像
这样的变量$var = staticVars::$host3;
不是我想要的是基于某些条件,静态变量应该在某些条件下返回值。如下所示,
class staticVars{
public static $host1 = 'www.host1.com';
public static $host2 = 'www.host2.com';
if(condition){
public static $host3 = 'www.host31.com';
}
else{
public static $host3 = 'www.host32.com';
}
public static $host4 = 'www.host4.com';
}
如何做到这一点,因为显然这是无效的。另外,我不想先创建对象。我需要它静静地完成。
答案 0 :(得分:0)
改为使用静态函数:
$(document).ready( function() {
$("input").keyup( function() {
// Cache current input user was typing in as jQuery object
var $input = $(this);
// Find first td in tr of the input user was typing
var $firstTd = $input.parent().prev();
// Find last td in tr of the input user was typing
var $lastTd = $input.parent().next();
// Compare text value of first td with value user typed in input
if ($firstTd.text() === $input.val()) {
// If equal find span in last td and set display block
$lastTd.find('span').css('display', 'block');
}
else {
// If not equal find span in last td and set display none
$lastTd.find('span').css('display', 'none');
}
});
});
并致电
class staticVars{
public static function getHost($number) {
switch($number) {
case '1':
return (condition) ? 'www.host1.com' : 'www.host31.com';
break;
}
}
}
阅读评论我看到OP不可能。所以,我认为通过静态方法初始化var可以解决问题:
staticVars::getHost(1);
答案 1 :(得分:0)
你可以使用常数?
class staticVars{
public static $host1 = 'www.host1.com';
public static $host2 = 'www.host2.com';
public static $host3 = _HOST3_;
public static $host4 = 'www.host4.com';
...
}
在constant.php
文件中,或config.php
或您想要的任何内容(具体取决于您的情况):
if(condition)
{
define('_HOST3_', 'www.host31.com');
}else{
define('_HOST3_', 'www.host32.com');
}