使用isset()的自定义函数在使用时返回未定义的变量

编程入门 行业动态 更新时间:2024-10-27 07:19:45
本文介绍了使用isset()的自定义函数在使用时返回未定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个字段,如果满足特定条件,则该字段具有自定义文本...如果不是,则该字段为空白.

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()的自定义函数在使用时返回未定义的变量

本文发布于:2023-10-11 17:42:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482384.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   变量   函数   未定义   isset

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!