Jump to content

Simple problem with variable scope.


AbydosGater

Recommended Posts

Hey guys,

Been awhile since i have had time to do any php but this is driving me mad.

 

I am setting two variables $comPost and $comAction.. Now if i echo these right after declaration, they work fine.

But inside the displayForm() function, if i set them as global they will not echo, but if i set any other predefined variable as global they work.

 

Code:

<?php
$args = explode('/', $params);
$comPost = $args[0];
$comAction = $args[1];
echo "/".$comPost.":".$comAction."/"; // This echos correctly.
function displayForm()
{
global $comPost, $comAction;
echo "displayForm()";
echo "<br />";
echo "/".$comPost.":".$comAction."/"; //This doesnt show the variables?
}
displayForm();
?>

 

Anyone know why, even though the variables are global they dont work inside the function?

 

Thanks for reading,

Andy

Link to comment
Share on other sites

I just tried your code and it works fine for me...

 

Why don't you just pass the variables into the function, instead of using the global?

 

<?php
$args = explode('/', $params);
$comPost = $args[0];
$comAction = $args[1];
echo "/".$comPost.":".$comAction."/"; // This echos correctly.
function displayForm($comPost,$comAction)
{
echo "displayForm()";
echo "<br />";
echo "/".$comPost.":".$comAction."/"; //This doesnt show the variables?
}
displayForm();
?>

 

Ken

Link to comment
Share on other sites

Yeah i was thinking about doing that,

Just an easy work around, but i was still wondering why it wasnt declaring the variables global.

 

It works with any other variable i have predefined.. Like if i declare $config as global i can echo that.

 

But just before if i set $myVar = "test"; and global it inside the function it doesnt recognise it either.

 

Find it odd. you say it works for you?

Maybe something in the settings?

 

Andy

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.