将变量作为参数默认值的 PHP 函数 [英] PHP function with variable as default value for a parameter

查看:40
本文介绍了将变量作为参数默认值的 PHP 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,PHP 函数使用 $_GET 变量.有时应该在未设置 $_GET 的情况下调用此函数.在这种情况下,我将定义所需的变量作为参数,如:actionOne(234)

为了得到一个抽象代码,我尝试了这样的事情:

function actionOne($id=$_GET["ID"])

导致错误:

<块引用>

解析错误:语法错误,意外的 T_VARIABLE

难道不能用变量来定义默认参数吗?

编辑

actionOne 使用框架 Yii 从 URL 中直接"调用.通过在这个函数之外处理 $_GET 变量,我不得不在一个中心组件上做这个(即使它是一个简单的、无关紧要的函数)或者我必须改变框架,我不喜欢要做.

执行此操作的另一种方法可能是由 URL 调用的虚拟函数(类似于前置函数).这个虚拟"函数处理变量问题并调用 actionOne($id).

解决方案

不,这是不可能的,正如 函数参数手册页:

<块引用>

默认值必须是常量表达式,而不是(例如)a变量、类成员或函数打电话.

相反,您可以简单地传入 null 作为默认值并在您的函数中更新它...

function actionOne($id=null) {$id = isset($id) ?$id : $_GET['ID'];....}

...或者(更好),当您没有要传入的特定 ID 时,只需提供 $_GET['ID'] 作为参数值.(即:在函数外处理.)

By default a PHP function uses $_GET variables. Sometimes this function should be called in an situation where $_GET is not set. In this case I will define the needed variables as parameter like: actionOne(234)

To get an abstract code I tried something like this:

function actionOne($id=$_GET["ID"])

which results in an error:

Parse error: syntax error, unexpected T_VARIABLE

Is it impossible to define an default parameter by using an variable?

Edit

The actionOne is called "directly" from an URL using the framework Yii. By handling the $_GET variables outside this function, I had to do this on an central component (even it is a simple, insignificant function) or I have to change the framework, what I don't like to do.

An other way to do this could be an dummy function (something like an pre-function), which is called by the URL. This "dummy" function handles the variable-issue and calls the actionOne($id).

解决方案

No, this isn't possible, as stated on the Function arguments manual page:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Instead you could either simply pass in null as the default and update this within your function...

function actionOne($id=null) {
    $id = isset($id) ? $id : $_GET['ID'];
    ....
}

...or (better still), simply provide $_GET['ID'] as the argument value when you don't have a specific ID to pass in. (i.e.: Handle this outside the function.)

这篇关于将变量作为参数默认值的 PHP 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆