英文:
PHP Automatic Function Arguments and Variables
问题
我想尝试实现类似于Codeigniter系统中的分段结构。
我想将通过REQUEST_URI获得的参数传递给一个函数,并在函数内部使用我想要的变量名调用它们。
示例:/news/stock
$arguments = explode('/',$_SERVER['REQUEST_URI']);
// 我想将这个数组传递给一个名为route的函数。
// 但我想这样调用它。
call_user_func('route', $arguments);
// 这里参数是作为数组传递的,但下面是我想要的。
function route($page,$slug)
{
//...
}
参数可以不止一个。我希望在函数中自己指定参数的名称,按参数的顺序。
你能帮助我处理这个问题吗?
英文:
I'm trying to do something similar to the segment structure in the Codeigniter system.
I want to transfer the parameters I get via REQUEST_URI to a function and call them with a variable name I want inside the function.
Example: /news/stock
$arguments = explode('/',$_SERVER['REQUEST_URI']);
// I want to pass this array to a function called route.
//But I want to call it like this.
call_user_func('route', $arguments);
// Here the arguments go as arrays but below is what I want.
function route($page,$slug)
{
//...
}
Parameters can be more than one. I want to specify the names in the function arguments in the function itself, in order of parameters.
Would you help me with this topic ?
答案1
得分: 1
Sure, here is the translated code part:
我假设你正在寻找扩展运算符。
或者在PHP中被称为参数解包。
https://www.php.net/manual/en/functions.arguments.php
尝试这个:
```php
route(...$arguments);
我更新了你的代码以更好地理解。
$arguments = explode('/',$_SERVER['REQUEST_URI']);
route(...$arguments);
// 这里的参数正如你想要的那样传递!!!
function route($page, $slug)
{
echo $page;// 新闻
echo $slig;// 股票
}
<details>
<summary>英文:</summary>
I assume you're looking for spread operator.
Or in PHP known as arguments unpacking.
https://www.php.net/manual/en/functions.arguments.php
Try this:
route(...$arguments);
I update your code to understand better.
$arguments = explode('/',$_SERVER['REQUEST_URI']);
route(...$arguments);
// Here the arguments going as you want!!!
function route($page,$slug)
{
echo $page;// news
echo $slig;//stock
}
</details>
# 答案2
**得分**: 0
尝试这个:
```php
$arguments = explode('/', $_SERVER['REQUEST_URI']);
function route($arguments) {
if (isset($arguments[1]) && $arguments[1] == 'news' && isset($arguments[2])) {
$page = isset($arguments[1]);
$slug = isset($arguments[2]);
echo $page . ' - ' . $slug;
}
}
英文:
Try this:
$arguments = explode('/',$_SERVER['REQUEST_URI']);
function route ($arguments) {
if (isset($arguments[1]) && $arguments[1] == 'news' && isset($arguments[2])) {
$page = isset($arguments[1]);
$slug = isset($arguments[2]);
echo $page . ' - ' . $slug;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论