Forum Moderators: coopster
I'm having some problem accessing variables I think I should be able to from within a function and later on in my php code. I hope the description below provides a clear picture of what I am doing.
My code is in this style
<?
$somelocalvariables;
function someFunction()
{
// cannot access "$somelocalvariables" here
}
?>
<SomeHTML>
<?
// cannot access "$somelocalvariables" here
?>
As usual, any help is greatly appreciated :)
Thanks everyone
The scope of the variable you set outside the function doesnt extend inside the function, so you won't be able to access it. So if you have:
$somevar = 'value';
function someFunction(){
echo $somevar;
}
somefunction();
it won't echo anything. You have options, depending on what you want to do.
first, pass the var as an argument to the function such as:
$somevar = 'value';
function someFunction($argument){
echo $argument;
}
someFunction($somevar);
The other option is to declare the variable global inside the function. This can sometimes make bugs difficult to track though, because then all the changes you make to the var inside the function will be reflected even after the fnction has finished. It is better to encapsulate the code in small independent chunks so if there is a bug you don't have thousands of places to look. In the example above, the var is not passed directly, i.e. a copy of the var is passed (depending on the datatype though...) so if you change it inside the function, it won't be reflected in subsequent uses of the var outside the function.
$somevar = 'value';
function someFunction(){
global $somevar;
echo $somevar;
}
The reason is that I need to access those variables twice (at this moment).
Once to validate.
Then once to echo in the form, if a user submit's data and some forms are invalid (so they don't have to retype their data in).
I think I'll go back to my old ways and just no put this stuff in a function.
It seems more practical than what I have now.
Let me know your thoughts though :)
function fValidate($data){
foreach($data as $key=>$entry){
if(condition to validate entry){
$data[$key] = $entry; //the entry is valid
} else {
$data[$key] = '';//entry is not valid, so clears it
}
}
return $data;
}
//put your post values in an array here
$data['name'] = $_POST]['name'];
etc...
//validate
$data = fValidate($data);
//do what you want with it here! Only the validated fields are still part of the array, non-valid fields are empty. You can, for example, echo each of $data's values in their proper html form field, since invalid data will be cleared and valid data won't need to be reentered