PHP私有变量未定义'虽然定义了

时间:2016-11-11 20:21:23

标签: php

我一直在玩RuneScape的核心形象创作者。人们倾向于在论坛上的个人资料中使用这些签名。

在重新编写一些代码时,我打破了它。我得到了:

  

未定义的变量:第8行的/assets/user.php中的exp   致命错误:无法访问第8行/assets/user.php中的空属性

然而,变量甚至不在第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;
}
}
?>

我在使用$ names时遇到错误,但那是因为我在函数中没有使用全局$ name。

1 个答案:

答案 0 :(得分:2)

您使用了错误的语法。

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

即。将return $this->$exp[0];更改为return $this->exp[0];