2016-11-11 100 views
0

我一直在玩弄一個RUNESCAPE hiscore形象的創造者。人們傾向於在論壇上使用這些簽名來簽名。PHP私有變量是「未定義」,雖然它被定義

而返工的一些代碼,我把它弄壞了。我越來越:

Undefined variable: exp in /assets/user.php on line 8 Fatal error: Cannot access empty property in /assets/user.php on line 8

然而,該變量甚至沒有在第8行(我假設的東西,用它做修剪空格)。

這裏是我的user.php的文件

<?php 

class User { 

public static $names = ["Overall", "Attack", "Defence", "Strength", "Hitpoints", "Ranged", "Prayer", "Magic", "Cooking", 
"Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining","Herblore", "Agility", "Thieving", "Slayer", 
"Farming", "Runecrafting", "Hunter", "Construction", "Summoning","Dungeoneering", "Divination", "Invention"]; 

private $user; 
private $mySkills = []; 
private $exp = []; 

public function __construct($result) { 
    $array = explode(",", $result); 
    $id = 0; 
    $arrId = 1; 
    while($arrId < count($result)) { 
     $this->$mySkills[$id] = $array[$arrId++]; 
     $temp = explode(" ", $array[$arrId++]); 
     $this->$exp[$id++] = $array[0]; 
    } 
} 

public function getTotalXp() { 
    return $this->$exp[0]; 
} 

public function getLevel($skill) { 
    global $names; 
    for ($x = 0; $x <= count($names); $x++) { 
     if(strcasecmp($skill, $names[$x]) == 0) { 
      return $this->$mySkills[$x]; 
     } 
    } 
    return 0; 
} 

public function getExp($skill) { 
    global $names; 
    for ($x = 0; $x <= count($names); $x++) { 
     if(strcasecmp($skill, $names[$x]) == 0) { 
      return $this->$exp[$x]; 
     } 
    } 
    return 0; 
} 
} 
?> 

我正在用$名稱錯誤,但那是因爲我沒有使用在函數全局$名稱。

+1

'$此 - > $ mySkills'和'$此 - > $ exp'是__wrong__語法 –

+1

...寫你對象的屬性爲:'$ this-> mySkills','$ this-> exp'等等 – SergeyLebedev

回答

2

您使用了錯誤的語法。

使用$this->variableName$this->$variableName

即改變return $this->$exp[0];return $this->exp[0];

+0

我現在正在爲我的數組索引0獲取未定義的索引錯誤。雖然它們應該在構造函數中設置,但是看到它們被設置的好方法是什麼? – Jesse

+0

創建User類的實例後,使用getter方法查看是否設置了任何內容。 – Daniel

+0

它顯示它沒有設置。我應該如何在構造函數中設置變量,以便它們與類的實例一起工作?現在的實例是:'$ user = new User($ result);',和mySkills/exp應該在構造函數中設置,但不是。我加了'echo'Setting'。 $ id。 ' 至 ' 。 $ array [$ arrId]'給構造函數,頁面上什麼都沒有顯示。 – Jesse

相關問題