Welcome Guest, Not a member yet? Register   Sign In
Hello
#1

[eluser]halwaraj[/eluser]
I have two functions. I need to access values from one in other how do i do it?

Here is what i want to do.


Code:
function a(){
    $a=1;
    $b=2;
}


now, I need to use the variables from the above function in otr func.


Code:
function b(){
    echo $c=$a+$b;
}




I tried global but no luck. Here is what I tried:


Code:
<?php

    $a,$b;

    class R{

        function a(){

            global $a,$b;

            $a=1;

            $b=2;

        }



        function b(){

            global $a,$b;

            $c=$a+$b;

            echo $c;

        }

    }

?>




As soon as I come to function b, $a and $b are empty.

How do I access those values?
#2

[eluser]alanphil[/eluser]
(NOTE: I'm taking a Java class this semester, which may be screwing with my ability to think in PHP. I'm sure a PHP guru will correct me if I'm wrong!)

You have a Class R with two defined methods. Make your variables "instance variables" of Class R (not outside the class). Then these variables will be available to any methods in Class R.

Alan
#3

[eluser]mdowns[/eluser]
I try to avoid globals whenever possible. You can use class members like so:
Code:
<?php

    class R{
        var $a,$b;
        function a(){

            $this->a=1;

            $this->b=2;

        }

        function b(){

            var $c = $this->a + $this->b;

            echo $c;

        }

    }

?>




Theme © iAndrew 2016 - Forum software by © MyBB