Reputation: 83
I have in my mind what I need to do to make the arg value available to all of the included functions that I am pulling into this script. As I am fairly new with the concept of functions, I am a bit lost as to why this doesn't work as I am thinking it would.
I am calling this script and passing an arguement at commandline. In this case I will use:
php mode_set.php test
I first tried setting a variable for the arguement value:
$mode = $argv[1];
and just referencing the value; however, I quickly learned that it wouldn't be available to other functions.
This led me to realize that in order for it to be available to other functions, I needed to create a function for it:
<?php
$mode = $argv[1];
//Returns the Mode Value
function show_mode()
{
if($mode == "test")
{
return "test";
}
elseif($mode == "parse")
{
return "parse";
}
else
{
return "false";
}
}
if(show_mode() == "test")
{
Do something useful...not working.
}
?>
What I am getting is it seems to be ignoring the arguement, and instead always passes false.
Upvotes: 1
Views: 132
Reputation: 76666
You can't access $mode
because it is outside the scope of the function; that is, PHP can only see the variables within the function when it's inside it. For $mode
to be accessible inside the function, you need to pass it as an argument: function($arg)
.
Your function can be simplified to just:
function show_mode($mode)
{
if ($mode == "test" || $mode == "parse") {
return $mode;
}
return FALSE;
}
In simple English: if $mode
is either test
or parse
, return $mode
. Otherwise return FALSE
.
Calling the function:
$mode = $argv[1];
echo show_mode($mode);
Upvotes: 2
Reputation: 219924
There's no reason why that variable would not be available to other functions since it is in the global namespace. You probably are making the same error as you are making below.
It's not available to that function unless you pass it as a parameter or use the global keyword:
Method 1: pass as parameter (recommended)
$mode = $argv[1];
//Returns the Mode Value
function show_mode($mode)
{
if($mode == "test")
{
return "test";
}
elseif($mode == "parse")
{
return "parse";
}
else
{
return "false";
}
}
Method 2: use global
keyword (not recommended)
$mode = $argv[1];
//Returns the Mode Value
function show_mode()
{
global $mode;
if($mode == "test")
{
return "test";
}
elseif($mode == "parse")
{
return "parse";
}
else
{
return "false";
}
}
Upvotes: 3
Reputation: 23510
You need to pass your argument to your function
$mode = $argv[1];
//Returns the Mode Value
function show_mode($mode)
{
Upvotes: 1