Jump to content

[SOLVED] How to get value?


atulkul

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/52635-solved-how-to-get-value/
Share on other sites

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.

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.