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

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

问题描述

默认情况下,PHP函数使用 $ _ GET 变量。有时候这个函数应该在未设置 $ _ GET 的情况下调用。在这种情况下,我将把需要的变量定义为如下参数: actionOne(234)



我试过这样的事情:

  function actionOne($ id = $ _ GET [ID])
code>

导致错误


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

是否不可能通过使用变量?



编辑


$ b $ < actionOne 通过使用框架 Yii 的URL直接调用。通过处理这个函数之外的 $ _ GET 变量,我必须在中心组件上做这件事(即使它是一个简单的,不重要的函数),或者我必须更改框架,我不喜欢这样做。



另外一种方法可以是一个虚函数(类似于函数前函数),它由URL调用。这个dummy函数处理变量问题并调用 actionOne($ id)

解决方案

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


默认值必须是常量
表达式,不是(例如)
变量,类成员或函数
调用。或者只是传递null作为默认值,并在你的函数中更新它。

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

...或(更好) ,只要提供$ _GET ['ID']作为参数值,当你没有特定的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天全站免登陆