Nathan
Nathan

Reputation: 384

How to store a PHP variable in a "global" way?

That may not be the correct terminology, "global".

What I'm trying to figure out is this.

I've got something like:

<?php if (empty($nest)) {
   $mothercrying = 'all day long';
   echo 'Mother is crying '.$mothercrying;
} if (!empty($nest)) {
   echo 'Mother is NOT crying '.$mothercrying;
} ?>

Is there some way to declare $mothercrying inside of the first if so that I can use it in the second one, too?

Note that I can't declare $mothercrying before both if statements, as what I'm working with is actually a couple of hundred lines longer than this.

Upvotes: 0

Views: 41

Answers (3)

momouu
momouu

Reputation: 711

Use session

  session_start();

if (empty($nest)) {
   $mothercrying = 'all day long';
   $_SESSION['cry']= $mothercrying;
   echo 'Mother is crying '.$_SESSION['cry'];
} if (!empty($nest)) {
  if(isset($mothercrying)){
    $_SESSION['cry']= $mothercrying;
  }else{
    $_SESSION['cry']='all day long';
  }        
   echo 'Mother is NOT crying '.$_SESSION['cry'];
}

Upvotes: 0

Marc Anton Dahmen
Marc Anton Dahmen

Reputation: 1091

That is not a "global" issue. Both confitions are excluding each other. The second if should just be an else and your variable must be defined before your if statement. In case the second confition is true, the first one can only be false and your variable won't be defined!

Upvotes: 0

Waqas Shahid
Waqas Shahid

Reputation: 1060

In both ways you can define constants, If you're defining constants in separate file then must include that file where you want to use:

define('MOTHER_CRYING', 'all day long');

OR

global $mothercrying;
$mothercrying = 'all day long';

Upvotes: 1

Related Questions