如何在另一个函数php中使用变量

时间:2014-04-22 15:40:02

标签: php variables scope global

 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;

}

如何在函数pokemon2()中使用函数pokemon1()的$ path变量? 我尝试使用&#34; global&#34;声明outsite函数。但仍显示未定义!

4 个答案:

答案 0 :(得分:1)

通过引用(&)使用它,然后将其传递到pokemon2

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

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

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

答案 1 :(得分:0)

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

但是你必须在调用pokemon2之前调用pokemon1

答案 2 :(得分:0)

你必须将Pokemon 1中的变量设置为全局,在你这样做之后,确保先调用函数Pokemon 1,否则pokemon 2中的变量与pokemon 1中的变量将是未定义的。

另外,为什么不直接声明函数范围之外的变量?

 $path = "";

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

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

答案 3 :(得分:0)

我们不应该修复[有问题的]提供的代码,而应该回答面向对象重构的绝望调用:

// 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);

当然你应该阅读更多有关此事的内容,但这取决于你。