我有一个字段,如果满足特定条件,则该字段具有自定义文本...如果不是,则该字段为空白.
I have a field that depends has custom text if a certain condition is met...and if it isn't the field is blank.
我写了一个自定义功能测试,是否设置了变量
I have written a custom function test if a variable is set
function AmISet($fieldName) { if (isset($fieldName)) { echo "I am set"; }else{ echo "I am not set"; } };但是当我将其附加到字段时,我得到一个错误,指出该变量未定义.但是当我执行常规的isset($fieldName); 我没问题有什么办法可以解决这个问题,并让我的函数代替isset()吗?
but when I attach it the field I get an error that the variable is undefined. But when I do a regular isset($fieldName); I don't have a problem. Is there any way to get around this and have my function do this instead of the isset()?
我想在函数中添加其他逻辑,但是我只希望它在设置了变量的情况下起作用...但是我不希望未定义的错误.
I want to add other logic in the function but I only want it to work if the variable is set...but I don't want the undefined error if it is not.
我是php的新手,非常感谢您能给我的任何帮助或指导. 谢谢您的帮助!
I am new to php and really appreciate any help or direction you can give me. Thank you for the help!
推荐答案您需要通过引用传递变量:
You need to pass the variable by reference:
function AmISet(&$fieldName) { if (isset($fieldName)) { echo "I am set\n"; } else { echo "I am not set\n"; } }测试用例:
$fieldName = 'foo'; AmISet($fieldName); // I am set unset($fieldName); AmISet($fieldName); // I am not set但是,此函数实际上没有用,因为它只会输出一个字符串.您可以创建一个接受变量的函数,如果变量存在则返回(来自此帖子):
However, this function is not useful as it is, because it will only output a string. You can create a function that accepts a variable and return if it exists (from this post):
function issetor(&$var, $default = false) { return isset($var) ? $var : $default; }现在可以像这样使用了:
Now it can be used like so:
echo issetor($fieldName); // If $fieldName exists, it will be printed更多推荐
使用isset()的自定义函数在使用时返回未定义的变量
发布评论