我正在使用定义功能根据性别改变国籍(Im Italian因性别而异)。代码有效,但是当我用MySQL中的其他函数更改函数参数时,函数停止工作。
define("ITA", serialize(array("m" => "italiano", "f" => "italiana")));
define("ENG", serialize(array("m" => "inglese", "f" => "inglese")));
define("RUS", serialize(array("m" => "russo", "f" => "russa")));
function nationality($code, $gender) {
$nationality = unserialize($code);
return $nationality[$gender];
}
echo nationality(ENG,'f'); //WORKS
$nationality = $author['nationality'];
echo nationality($nationality,'f'); //DOESNT WORKS
编辑:$ author ['nationality'];取自MySQL
答案 0 :(得分:5)
这是因为你将字符串传递给你的函数而不是常量。
我在这里猜测,但看起来像$author['nationality']
似乎是' ENG',' ITA'要将字符串作为常量使用constant()
函数传递,如下所示:
echo nationality(constant($nationality),'f');
答案 1 :(得分:2)
源文件中仅存在ENG
之类的常量。您不能将它们视为常规字符串。你永远不会使用/传递一个常量,你只使用/传递映射值。
您可以使用内置constant
来查找映射:
constant($nationality)
但如果您只需要按字符串查找值,请将它们存储在array
中。
(注意:也不需要序列化)
$languages = array(
"ITA" => array("m" => "italiano", "f" => "italiana"),
...
);
并使用
$languages[$nationality]
答案 2 :(得分:2)
尝试使用代码:
define("ITA", serialize(array("m" => "italiano", "f" => "italiana")));
define("ENG", serialize(array("m" => "inglese", "f" => "inglese")));
define("RUS", serialize(array("m" => "russo", "f" => "russa")));
function nationality($code, $gender) {
if(defined($code)) {
$nationality = unserialize(constant($code));
return $nationality[$gender];
}
return false;
}