PDA

Click to See Complete Forum and Search --> : [RESOLVED] Quick function question


KiwiDexter
Jun 14th, 2009, 09:55 PM
I want to do something like

$value = update_text($value)

function text_process($value){
$value = trim(strip_tags($value));
$value = addslashes($value);
$value = htmlspecialchars($value);
}

Do I need to return $value in order to have it available to the code that calls the function or is it already loaded into the calling value "$value ="

SambaNeko
Jun 15th, 2009, 01:41 AM
You will need to return it. Or, if desired, you could pass $value by reference by making this change:


function text_process(&$value){


If you did it that way, no return is necessary, and you'd only need this when calling it:


text_process($value);


(Your sample function call is different from your function definition here - I'm sticking with "text_process" for both...)

KiwiDexter
Jun 15th, 2009, 05:55 PM
You will need to return it. Or, if desired, you could pass $value by reference by making this change:


function text_process(&$value){


If you did it that way, no return is necessary, and you'd only need this when calling it:


text_process($value);


(Your sample function call is different from your function definition here - I'm sticking with "text_process" for both...)

Oops sorry, still playing around with names to get some sort of logic into what functions are called.

So if I modify the variable I pass in the function list the changes are reflected in the calling script?

SambaNeko
Jun 15th, 2009, 08:49 PM
So if I modify the variable I pass in the function list the changes are reflected in the calling script?

You're not really modifying the variable, just changing what the function does with the variable...

The default behavior of a function is to take input variables by value. Like this:


function addTwo($number){
return $number + 2;
}

$num = 1;
$newNum = addTwo($num);


At the end of that block of code, $newNum is 3, but $num is still 1, because the function took the value of $num, added two, then put the result into $newNum. It didn't change the value of $num.

Adding the & prior to a variable in the function definition makes the function take the variable by reference instead. Which changes things...


function addTwo(&$number){
$number += 2;
}

$num = 1;
addTwo($num);


In this case, the value of $num at the end of the code is 3, because the function took a reference to the variable $num, and added two to the variable that was referenced.

So, as said, you could do it either way - you can add a return to get the altered value from your function, or add the & to have it alter your variable directly.

KiwiDexter
Jun 15th, 2009, 09:25 PM
Thanks for the answer dude, think I'll settle on the "return" option as it makes it more readable. :)