Question

 function pokemon1()
{ 
include 'details.php';
 $path = $_SESSION['path'];
 $health = $_SESSION['health'];
 echo "<br />";
 echo $path;
 echo "<br />";
 echo $health;
}


function pokemon2()
{
include 'details.php';
 $flag =  $_SESSION['flag'];
 $damage = $_POST['attack']; 
 $oppo_health = $_SESSION['oppo_health']; 

 $oppo_path = $_SESSION['path'];
 echo "<br />";
 echo $oppo_path;
 echo "<br />"; 
   $oppo_health = $oppo_health - $damage;
  echo $oppo_health;
 $_SESSION['attack'] = $damage; 
 $_SESSION['oppo_health'] = $oppo_health;

}

How can I use the $path variable of function pokemon1() in function pokemon2()??? I tried declaring outsite the function with "global" but still its showing undefined!

Was it helpful?

Solution

You have to set the variable inside Pokemon 1 to global, after you do that, make sure you call function Pokemon 1 first, else the variable inside pokemon 2 with the variable from pokemon 1 will be undefined.

Also, why don't you just declare the variable outside the scope of a function?

 $path = "";

function pokemon1(){
    ....
    global $path...;
}

function pokemon2(){
   ....
  global $path...;
}

OTHER TIPS

function pokemon2()
{
global $path;
...
}

But u have to call pokemon1 before calling pokemon2

Use it by reference (&), then pass it into pokemon2

$path = "";
pokemon1($path);
pokemon2($path);    

function pokemon1(&$path) {
 $path = $_SESSION['path'];
}

function pokemon2($path) {
 //$path = $_SESSION['path'];
}

Instead of fixing the [questionable] provided code, we should answer the desperate call of object-oriented refactoring:

// define the class

class Pokemon
{

  protected $path;
  protected $health;
  protected $attack;

  public function __construct($path, $attack = 10, $health = 100)
  {

    $this -> setPath($path);
    $this -> setAttack($attack);
    $this -> setHealth($health);

  }

  public function setPath($path){ $this -> path = $path; }
  public function getPath(){ return $this -> path; }

  public function setAttack($attack){ $this -> attack = $attack; }
  public function getAttack(){ return $this -> attack; }

  public function setHealth($health){ $this -> health = $health; }
  public function getHealth(){ return $this -> health; }

  public function attack(Pokemon $other)
  {

    $otherHealth = $other -> getHealth();
    $other -> setHealth($otherHealth - $this -> getAttack());

    // make further controls / bonuses / death...

  }

}

// use it sonewhere

include "path/to/your/class/file/Pokemon.php"

$pomemon1 = new Pokemon('dunno', 100);
$pomemon2 = new Pokemon('reallyDunno', 100);

$pokemon1 -> attack($pokemon2);

Of course you should read more about the matter, but this is up to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top