Jump to content

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'
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.