Jump to content

Getting stuff out of a function


Pezmc

Recommended Posts

I am not a newbie I have just never figured out how to do this (taught my self php).

I have a function say

function socks(test,sock) {
echo $test
echo "I am a fary:"
echo $sock

$total = $test * $sock;

}

 

How can I get the total out of the function to use in other places as a variable, is there a returning function or something?

Link to comment
https://forums.phpfreaks.com/topic/44928-getting-stuff-out-of-a-function/
Share on other sites

You need to have your function return the value. Then, you can assign that function call to a variable:

<?php
function socks($test, $sock) {
  $total = $test * $sock;
  return $total;
}

echo socks(5, 6);
$val = socks(6, ;
echo $val;
?>

You could also make the variables global inside the function, then it would, well, do it globally instead of internally inside the function. Example:

 

<?php
$var = "hi";

function change_variable($new)
{
global $var;

$var = $new; // or $_GLOBALS['var'] = $new
}

change_variable("hello"); // $var now holds the value "hello"
?>

You could also make the variables global inside the function, then it would, well, do it globally instead of internally inside the function. Example:

 

<?php
$var = "hi";

function change_variable($new)
{
global $var;

$var = $new; // or $_GLOBALS['var'] = $new
}

change_variable("hello"); // $var now holds the value "hello"
?>

 

Global variables are very often bad news to use. They are definitely frowned upon more and more as PHP progresses. If you're wanting your function to act upon the variable or object directly, you'd be much better off to pass it in by reference:

<?php
$var = "hi";
function change_variable($new, &$old) {
  $old = $new;
}

change_variable('hello', $var);
echo $var; // now holds the value 'hello'
?>

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.