2014-04-22 74 views
0
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變量? 我試過用「global」聲明outsite函數,但仍然顯示undefined!如何在另一個函數中使用變量php

+0

這是怎麼回事[標籤:MySQL] ...? – webeno

回答

0

你不得不在屋裏口袋妖怪1變量設置爲全球化後,確保你先調用函數Pokemon 1,否則Pokemon 2中的變量與來自Pokemon 1的變量將不確定。

此外,爲什麼不只是聲明函數範圍之外的變量?

$path = ""; 

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

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

但你必須調用pokemon2

+0

nopes ..沒有幫助 – user3545779

1

引用(&)使用它之前調用pokemon1,然後將它傳遞到pokemon2

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

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

function pokemon2($path) { 
//$path = $_SESSION['path']; 
} 
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); 

當然,你應該閱讀更多關於此事,但這是向上給你。

相關問題