Jump to content

Global String


lucerias

Recommended Posts

I have started my learning on php few weeks ago, i found that the 'global' and 'local' really mess me up, i can't keep myself stick to way of using them because in VB and other languages, a predefined variable can be passed in function and overwrite the previous value if necessary.

However, when comes to php, i must be alert of that all the time since i had established the "No care" habit on it. Anyone can help me to solve the following code problem, the idea is to stripslashes the $value, which is a string defined locally and used in function and echo the final result eventually. Thank you.

<?php
$value="St\ring";

function stripslashes_checkstrings($value)

    global $value;
         
if(is_string($value))
    {
        stripslashes($value); 
}   
return $value;   
}
     
stripslashes_checkstrings($value);
echo $value;

?>

I did this by referring to the following code,

<?php
$a = 1;
$b = 2;

function Sum()
{
  global $a, $b;

  $b = $a + $b;
}

Sum();
echo $b;
?>
Link to comment
https://forums.phpfreaks.com/topic/22824-global-string/
Share on other sites

what you want to do is either pass in the variable to the function either [i]as a reference[/i] or [b]return the new value[/b] from the function instead:
[code]
<?php
// first option: pass by reference
function stripslashes_checkstrings(&$value) {
  if (is_string($value)) {
    $value = stripslashes($value);
  }
}

$value = "St\ring";
stripslashes_checkstrings(&$value);
echo $value;

// second option: return a value
function stripslashes_checkstrings($value) {
  if (is_string($value)) {
    $value = stripslashes($value);
  }
  return $value;
}

$value = "St\ring";
$value = stripslashes_checkstrings($value);
echo $value;
?>
[/code]

good luck
Link to comment
https://forums.phpfreaks.com/topic/22824-global-string/#findComment-102807
Share on other sites

the lack of the 'r' is due to the fact that "\r" is a carriage return, and if you read the manual for stripslashes, it only works on [i]quotes[/i]. read up on the manual page for stripslashes to see what the deal is. if you're wanting to remove [b]all[/b] slashes completely (which could be dangerous), you'd have to write your own function.

as for the ampersand, that is how you tell PHP to pass the variable by [i]reference[/i] instead of by [i]value[/i].
Link to comment
https://forums.phpfreaks.com/topic/22824-global-string/#findComment-103000
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.