Perocat
Perocat

Reputation: 1521

function returns false - but I'm sure it should be true

I have this string:

$currentpath = basename(__FILE__);

If I write

echo $currentpath;

It returns navleft.php

Now my function:

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

but if I call the function

colorButton();

I always get navbuttonoff.

Why is this the case?

Upvotes: 0

Views: 49

Answers (3)

Yevgen
Yevgen

Reputation: 1300

You can't call vars from function like this...

It should be like

<?
$currentpath = 'navleft.php';
function colorButton() {

  global $currentpath;

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

OR like this

<?
$currentpath = 'navleft.php';
function colorButton($currentpath) {

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

Upvotes: 0

Supericy
Supericy

Reputation: 5896

You either need to:

1. Use a global

function colorButton() {
    global $currentpath;

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

OR, the better solution:

2. Pass the path in as an argument

function colorButton($currentpath) {

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

colorButton($currentpath);

Things you should learn about:

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

Upvotes: 0

John Conde
John Conde

Reputation: 219804

You need to learn about variable scope. $currentpath is not available to colorButton unless you pass it as a parameter (or use evil things like global):

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

Perfect example from the manual:

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

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

test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope.

Upvotes: 4

Related Questions