Function, passing values to and from [SOLVED]

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
User avatar
Callan S.
Posts: 2042
Joined: Sun Jan 24, 2010 5:43 am

Function, passing values to and from [SOLVED]

Post by Callan S. »

I'm trying out using a function for the first time and wondering how to get values out of it.

Like if I have

Code: Select all

function testfunc($aaa,$bbb)
Then it'll use $aaa and $bbb inside it.

But what I want is to change values outside the function? Say I have $playermoney outside the function and I want the function to increase it when run?

When I've googled php they've only really given info on echoing out the values, it seems?

Easy question I'm sure alot of people on forum know! I know it's in one of the tute videos but I can't remember which one! Thanks!
Last edited by Callan S. on Sun Jul 31, 2011 1:39 am, edited 1 time in total.
User avatar
Callan S.
Posts: 2042
Joined: Sun Jan 24, 2010 5:43 am

Re: Function

Post by Callan S. »

After quite awhile I think I found a solution using 'global'

Code: Select all

<?php
session_start();

$num1 = "5";

if (!isset($_SESSION['test'])) $_SESSION['test']=5;

$num3=$_SESSION['test'];

function multi()

{

    global $num1,$_SESSION;

    $num1 +=10;
    $_SESSION['test']+=1;

}

multi();

echo $num1."<br>";
echo $_SESSION['test'];


?>
Had to fiddle around for it to pass over session arrays as well.

I'll test this a bit more and if it's working the way I want, I'll edit a solved onto the title of the thread.
User avatar
hallsofvallhalla
Site Admin
Posts: 12026
Joined: Wed Apr 22, 2009 11:29 pm

Re: Function

Post by hallsofvallhalla »

you can also use

return($variable);

http://php.net/manual/en/function.return.php
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: Function

Post by Xaleph »

It`s all about scope, baby!

No, i`m just trying to be funny, but the argument still stands. The function scope means something like this: If you want to use a function to do something, like transforming a string , you better return the string, otherwise the function has no meaning right?

let`s say you want to capitalize and format a string like this:

$string = str_replace(array("_","&","*","$","#"),"-",ucfirst(strtolower($string)));

So, if a given string is:

$string = owie$weB_qwoei%*we&ojw;
$string = str_replace(array("_","&","*","$","#", "&"),"-",ucfirst(strtolower($string)));

So, now $String would look like something like:

Owie-web-qwoei--we-ojw

But you don`t want to type it everyting:

function normalize($string){
$string = str_replace(array("_","&","*","$","#", "&"),"-",ucfirst(strtolower($string)));
}

Now, inside the function, the $string var is sanitized ( or whatever you want to name it.. it`s an example.. ) but how do you get that value back?
Just return the $string.

function normalize($string){
return str_replace(array("_","&","*","$","#", "&"),"-",ucfirst(strtolower($string)));
}

$string = owie$weB_qwoei%*we&ojw;
$string = normalize($string); // will be: Owie-web-qwoei--we-ojw

The thing is, you cannot use the $string inside the function, somewhere outside. Unless you use globals. And globals are an evil. Really. Because they mess up the default PHP stack. Using globals means you can access them anywhere at any time. But, if you already use globals, like $_SESSION, no real harm is done, but then again, you are using $_globals for a wrong reason, but that`s not too bad.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Function

Post by Jackolantern »

Do not use globals!!! It makes me angry they are even an option in PHP. Did we learn nothing from the last 2 decades of programming lol??

Ok, to get serious, globals lead to unmaintainable code, extremely difficult bugs to find, and a host of other issues. One of the worst being if you have hundreds of variables and lose track of what you have already made, and accidentally overwrite a variable that exists outside of a function with a global variable inside a function. Good lord, you better put some coffee on if you want to find that one tonight, because the problem will crop up in a totally different place than where the mistake was made.

There are a couple of option in this case. One, and probably the most simple, is to just return a value from a function, then operate with the value returned from the function. Of course, this is often not what you want, because you are trying to encapsulate the whole process in the function. Enter "passing by reference"!

Right now you may have something like this:

Code: Select all

function addOne($inVal) {
    $inVal++; //adding one
}

$val = 10;
addOne($val);
echo $val; //still 10
But now lets pass the value by reference:

Code: Select all

function addOne(&$inVal) {
    $inVal++; //adding one
}

$val = 10;
addOne($val);
echo $val; //woo! we have 11 now!
The magic is all in the "&" before the variable name in the function's parameter list. You do not use a "&" when you call the method anymore (you use to in earlier versions of PHP).

That should get it to do what you want without having to sacrifice too much control. Of course it is still against best practices to start loading up every function with pass-by-reference mechanics, or it can become difficult to tell where an error is being made if you have function calls nested inside each other several layers deep since PHP doesn't really have a good debugger. But it is much, much better than globals ;)
The indelible lord of tl;dr
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: Function

Post by Xaleph »

Oh i forgot you still have the & reference indeed. But that`s a bug/quirk too.. It was used to pass objects by reference as a quirk because PHP didn`t support call/pass by reference at the time ( PHP4 ).

Honestly, I would use the return in functions or go all the way and use objects instead. The reference operator works OK, but it`s really a quirk and support for it will be gone in PHP 5.4 and 6.0 ( whenever either of em come.. )
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Function

Post by Jackolantern »

It is a full feature of PHP today, not a quirk. Part of it is deprecated, but that is using the & operator in the function call itself. Pass-by-reference functions are not deprecated, nor are they likely to ever be, considering how much code that would break out there. Check out the PHP manual page. Anything to be removed from PHP must go several versions as deprecated to warn people not to use it, and it is not marked as such. I can't find anything online calling it a quirk, or a bug or anything. It is an acknowledged feature of PHP. Where are you seeing that it will be removed from the next versions of PHP?
The indelible lord of tl;dr
User avatar
Callan S.
Posts: 2042
Joined: Sun Jan 24, 2010 5:43 am

Re: Function

Post by Callan S. »

Thanks all!

Jack,
I'd like to pass a session value directly to the function. I know I could pass a regular variable, then after calling the function set the session to equal it, but it seems clumsy that way - I'm using functions to keep things in one spot, after all.

But the following brings up an error?

Code: Select all

function multi(&$_SESSION['test'],&$num1)

Halls,

I'm looking at the return documents but not really getting it? When returned, it just seems to echo out the results? I must be reading it wrong?
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Function

Post by Jackolantern »

$_SESSION is known as a super global. It is already global, so really there is no reason to pass it into a function at all. Simply access the $_SESSION array in the function body, alter it anyway you want to, save a value back into it, etc.

Honestly, I don't know why that caused an error, as I have never tried to pass a super global array by reference into a function, but it makes sense to me that it wouldn't work.

Ohh, and when you return a value from a function, all that happens is that variable is passed back out of the function. If you call a function like this:

Code: Select all

echo myFunction($a);
Then whatever is returned by myFunction will be echo'd. However, if you did this, the value returned from myFunction would be saved into a regular variable, ready for whatever you want to do with it:

Code: Select all

$newVar = myFunction($a);
The indelible lord of tl;dr
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: Function

Post by Xaleph »

@Jack, it has been ages the last time i saw it was deprecated. But talking of which, I did look it up:

Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

Also:

The same syntax can be used with functions that return references, and with the new operator (since PHP 4.0.4 and before PHP 5.0.0):

Which is old ( < 5.0.0)

Everything is moving and making a shift to OO, which is good. But you can still use it. But call-by-reference should trigger the error anyway.
Post Reply

Return to “Beginner Help and Support”