PHP自动函数参数和变量

huangapple go评论56阅读模式
英文:

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&#39;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(&#39;/&#39;,$_SERVER[&#39;REQUEST_URI&#39;]);
function route ($arguments) {
if (isset($arguments[1]) &amp;&amp; $arguments[1] == &#39;news&#39; &amp;&amp; isset($arguments[2])) {
 $page = isset($arguments[1]);
 $slug = isset($arguments[2]);
 echo $page . &#39; - &#39; . $slug;
}

huangapple
  • 本文由 发表于 2023年3月4日 05:46:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632142.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定