atulkul Posted May 23, 2007 Share Posted May 23, 2007 I have initialized a value say $a = 50; in function first , like i would write the code so that it will be clear <? function first() { $a = 50; } function second() { // i want to get value of $a which is initialized in above funtion. } ?> ok here in function second() , i want the value of $a which is initialized in function first(). Can anybody help me out. Quote Link to comment https://forums.phpfreaks.com/topic/52635-solved-how-to-get-value/ Share on other sites More sharing options...
obsidian Posted May 23, 2007 Share Posted May 23, 2007 Well, as you stand, you only have functions, so it's not truly OOP yet. There are only a few ways to share values between functions. Since a variable that is instantiated within a function is only accessible for the scope of that function, you have to either return that value to the calling script or else have the functions within a class and instantiate a class member variable that is then accessible from within the second function. Examine the following two examples: <?php // Example 1 function first() { $a = 50; return $a; } function second() { $val = first(); // call the first() function from within the second() } // Example 2 class MyClass { var $a; function first() { $this->a = 50; } function second() { $val = $this->a; } } $class = new MyClass(); $class->first(); $class->second(); ?> The biggest thing to remember is to stay away from using global variables. There is almost always a much better and safer way to handle your variables. Quote Link to comment https://forums.phpfreaks.com/topic/52635-solved-how-to-get-value/#findComment-259779 Share on other sites More sharing options...
atulkul Posted May 23, 2007 Author Share Posted May 23, 2007 Hey Thanks. i wanted that only. Quote Link to comment https://forums.phpfreaks.com/topic/52635-solved-how-to-get-value/#findComment-259795 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.