Eggzorcist Posted June 28, 2009 Share Posted June 28, 2009 In my script I made a quick function which secures the inputed variable like this. function secure_var($var){ $var = mysql_real_escape_string(htmlentities($var)); } I have a quick question of something I'm unsure of. To use a variable like this one. Should I be doing... <?php $var = secure_var($var) // or would this just work? secure_var($var) ?> I will be retrieving the variable like "$var" I think the first option is best but I'm unsure of the right way of doing this. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/163991-solved-quick-variable-function-question/ Share on other sites More sharing options...
Alex Posted June 28, 2009 Share Posted June 28, 2009 To get a value from a function you use return: function secure_var($var){ return mysql_real_escape_string(htmlentities($var)); } $var = 'something...'; $var = secure_var($var); Quote Link to comment https://forums.phpfreaks.com/topic/163991-solved-quick-variable-function-question/#findComment-865095 Share on other sites More sharing options...
.josh Posted June 28, 2009 Share Posted June 28, 2009 to expand... functions have their own scope, so if you do this: function secure_var($var){ $var = mysql_real_escape_string(htmlentities($var)); } $var = "something"; secure_var($var); your function is going to do its thing on its own copy of $var, and nothing will happen with your $var. So you have to either return it, pass it by reference, or declare it as global inside your function. example of global: function secure_var($x){ global $var; $var = mysql_real_escape_string(htmlentities($x)); } $var = "something"; secure_var($var); passing by reference: function secure_var(&$var){ $var = mysql_real_escape_string(htmlentities($var)); } $var = "something"; secure_var($var); Best practice is to return assign the function to the value and return the results inside the function (as detailed by AlexWD's post), because one of the points of functions is that they have their own scope. Quote Link to comment https://forums.phpfreaks.com/topic/163991-solved-quick-variable-function-question/#findComment-865171 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.