Jump to content

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.

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.