【问题标题】:function returns false - but I'm sure it should be true函数返回 false - 但我确定它应该是 true
【发布时间】:2013-02-06 02:03:33
【问题描述】:

我有这个字符串:

$currentpath = basename(__FILE__);

如果我写

echo $currentpath;

它返回 navleft.php

现在我的功能:

function colorButton() {
    if($currentpath == "navleft.php") {
        echo "navbuttonon";
    } else {
        echo "navbuttunoff";
    }
}

但是如果我调用函数

colorButton();

我总是得到 navbuttonoff。

为什么会这样?

【问题讨论】:

  • 你舒尔你舒尔吗? :D

标签: php string function if-statement


【解决方案1】:

您需要了解variable scope$currentpathcolorButton 不可用,除非您将其作为参数传递(或使用诸如 global 之类的邪恶事物):

function colorButton($currentpath) {
if($currentpath == "navleft.php") {
    echo "navbuttonon";
} else {
    echo "navbuttunoff";
}
}

手册中的完美示例:

<?php
$a = 1; /* global scope */ 

function test()
{ 
    echo $a; /* reference to local scope variable */ 
} 

test();
?>

此脚本不会产生任何输出,因为 echo 语句引用 $a 变量的本地版本,并且尚未在此范围内为其分配值。

【讨论】:

  • 我真是个愚蠢的人......对不起,这是基本的...... :-(再次抱歉!
  • 不用担心。我们都去过那里。 :)
【解决方案2】:

您需要:

1.使用全局

function colorButton() {
    global $currentpath;

    if($currentpath == "navleft.php") {
        echo "navbuttonon";
    } else {
        echo "navbuttunoff";
    }
}

或者,更好的解决方案:

2。将路径作为参数传入

function colorButton($currentpath) {

    if($currentpath == "navleft.php") {
        echo "navbuttonon";
    } else {
        echo "navbuttunoff";
    }
}

colorButton($currentpath);

您应该了解的事项:

http://php.net/manual/en/language.variables.scope.php

【讨论】:

    【解决方案3】:

    你不能像这样从函数中调用 vars...

    应该是这样的

    <?
    $currentpath = 'navleft.php';
    function colorButton() {
    
      global $currentpath;
    
      if($currentpath == "navleft.php") {
        echo "navbuttonon";
      } else {
        echo "navbuttunoff";
      }
    }
    colorButton();
    

    或者像这样

    <?
    $currentpath = 'navleft.php';
    function colorButton($currentpath) {
    
      if($currentpath == "navleft.php") {
        echo "navbuttonon";
      } else {
        echo "navbuttunoff";
      }
    }
    colorButton($currentpath);
    

    【讨论】:

      猜你喜欢
      • 2016-04-16
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 2020-02-12
      • 2016-12-05
      相关资源
      最近更新 更多