Jump to content

Access variable inside function from another function ?!


vivis933

Recommended Posts

This an example of what i need , basically the variable from first function to be included in the second function.

<?php
$number1 = 6 ;
$number2 = 4 ;
$number3 = 2 ;
funct1($number1, $number2);
funct2($variable1 , $number3);
echo $variable2;

function funct1($number1, $number2)
{
$variable1 = $number1 + $number2 ;
}


function funct2($variable1 , $number3)
{
$variable2 = $variable1 / $number3 ;
}
?>

ERROR 

 

PHP Notice:  Undefined variable: variable1 on line 6

PHP Notice:  Undefined variable: variable2 on line 7

 

Edited by vivis933
Link to comment
Share on other sites

Well, this is not how variables work. A local variable is only visible within that function and gets destroyed immediately when the function returns.

 

I think what you actually want to do is return the result of the addition so that you can then use it outside of the function:

<?php

function add($number_1, $number_2)
{
    return $number_1 + $number_2;    // add the two numbers and return the result
}

function div($number_1, $number_2)
{
    return $number_1 / $number_2;
}



$sum = add(6, 4);
$quot = div($sum, 2);

echo $quot;
  • Like 1
Link to comment
Share on other sites

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.