Jump to content

[SOLVED] Quick Variable Function question


Eggzorcist

Recommended Posts

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

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/163991-solved-quick-variable-function-question/
Share on other sites

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.

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.