【问题标题】:PHP function call not working - presumed casting problem?PHP函数调用不起作用 - 假定的转换问题?
【发布时间】:2010-08-08 17:20:40
【问题描述】:

为什么这在通过例如调用时不起作用wd(1)(它总是返回'-2')?

$zoom=$user['zoom'];
function wd($hrs){
  return $hrs*$zoom-2;
}

但这很好用:

function wd($hrs){
  return $hrs*30-2;
}

假设这是一个选角问题,我尝试了各种变体,例如

(int)$hrs * ((int)$zoom)

(int)$hrs * (float)$zoom

但没有成功:(

任何帮助将不胜感激。

(顺便说一句,函数是否位于内部是否重要

include('header.php')

-- 虽然我在标题内外都试过了?)

【问题讨论】:

    标签: php function casting scope


    【解决方案1】:

    编辑:您应该将该变量作为参数传递给函数,但如果您绝对需要保持变量全局,请执行以下操作。

    您需要将全局纳入范围:

    $zoom=$user['zoom'];
    function wd($hrs){
      global $zoom;
      return $hrs*$zoom-2;
    }
    

    【讨论】:

    • 使用全局变量确实不太理想(尤其是在不需要它的情况下)。
    【解决方案2】:

    这不是强制转换问题 - 这是因为您尝试使用 out of scope 的变量。

    虽然您需要阅读 PHP 文档以了解完整的内容,但在基本层面上,您只能访问在同一函数或方法中定义的变量。 (虽然您可以使用global 关键字来访问全局变量。也就是说,全局变量并不理想。)

    因此,您可以简单地更新您的函数以将“缩放”作为参数传递,如下所示:

    function wd($hrs, $zoom){
      return $hrs*$zoom-2;
    }
    

    【讨论】:

    • @user381636 很可能是拼写错误或摘要。 :-)
    【解决方案3】:
    $zoom=$user['zoom'];
    function wd($hrs){
      // there is no variable $zoom within the function's visibility scope
      // so you will get a "Notice: undefined variable 'zoom'" here.
      return $hrs*$zoom-2;
    }
    

    http://docs.php.net/language.variables.scope

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      相关资源
      最近更新 更多