我在google和SO 上找不到我的问题。希望,我可以解释你。
了解以下功能时你会明白:
function get_page($identity)
{
if($identity is id)
$page = $this->get_page_from_model_by_id($identity);
elseif($identity is alias)
$page = $this->get_page_from_model_by_alias($identity);
}
get_page(5); // with id
or
get_page('about-us'); // with alias
or
get_page(5, 'about-us'); // with both
我想将参数发送到功能id
或alias
。它应该只是一个标识符。
我不想要function get_page($id, $alias)
如何只用一个variable
来获取和了解参数类型。有任何功能或可能吗?
答案 0 :(得分:1)
使用is_string()查找输入是整数还是字符。
答案 1 :(得分:1)
if(is_numeric($identity)) {
$page = $this->get_page_from_model_by_id($identity);
}
elseif(is_string($identity)) {
$page = $this->get_page_from_model_by_alias($identity);
}
elseif(func_num_args() === 2) {
$id = func_get_arg(0);
$alias = func_get_arg(1);
//do stuff
}
答案 2 :(得分:0)
您应该使用 func_get_args()
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
<强> Source 强>
答案 3 :(得分:0)
这是一个完整的解决方案:
function get_page()
{
$alias = false;
$id = false;
foreach(func_get_args() as $arg)
if(is_string($arg))
$alias = $arg;
else if(is_int($arg))
$id = $arg;
}
答案 4 :(得分:0)
假设id总是一个数字,你可以用php的is_numeric()
测试它function get_page($identity)
{
if(is_numeric($identity) {
$page = $this->get_page_from_model_by_id($identity);
} else {
$page = $this->get_page_from_model_by_alias($identity);
}
}