dpict99695329 2013-08-29 06:56 采纳率: 100%
浏览 6
已采纳

php传递一个并不总是在用户函数中设置的变量

i have created a simple function in php, but i'm not sure about how to pass a (optional) variabile if this is not always set, for example:

myfunction( $var1, $var2, $_POST[example] );

as you can see the myfunction is always called but the $_POST[example] isset/exist only when the form was already sent.

my question is, is that correct??? if $_POST[example] don't exist i see no error/notice (Notice: Undefined variable..) but i'm not sure...

maybe is better like this?

 myfunction( $var1, $var2, isset($_POST[example]) );
  • 写回答

5条回答 默认 最新

  • doudeng5218 2013-08-29 07:03
    关注

    As AlmaDoMundo's answer shows: make the argument optional:

    function myFunction($arg1, $arg2, $arg3 = null)
    {
    }
    

    Then, to avoid warnings (undefined index), you'll have to call the function like so:

    if (isset($_POST['example']))
    {
        myFunction($var1, $var2, $_POST['example']);
    }
    else
    {
        myFunction($var1, $var2);
    }
    

    If, for some reason you're unable to change the function definition (and therefore, it's signature), just call the function like this:

    $var3 = isset($_POST['example']) ? $_POST['example'] : null;
    myFunction($var1, $var2, $var3);//null is a value, so you're passing 3 arguments
    

    Calling the your function the second way myFunction($var1, $var2, isset($_POST['example'])); is not the way forward. Just look at isset's signature

    bool isset ( mixed $var [, mixed $... ] )
    

    it returns a bool (true/false), not the value of the variable itself. If the key exists, your function will receive true as a third argument, if not false. You want to pass the actual value, so you'll have to either wrap your code in if/else branches, or use a ternary (myFunction($var1, $var2, isset($_POST['example']) ? $_POST['example'] : null);.
    Personally, I'd not use a ternary here, because the first example of how to call the function I gave here is just much more readable (it's important to write maintainable code!)

    On the notice:
    You say you don't see any errors/warnings if you pass $_POST['example'] (you should quote the 'example', BTW, because that should issue a warning, too). Try changing your ini settings to:

    error_reporting  =  E_ALL | E_STRICT
    #and
    display_errors = 1
    display_startup_errors = 1 # careful here!
    

    Then, you'll see how many issues your code really has. Check the manual to see what each setting does, how and when to use them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b