Jesse Jesse - 22 days ago 10
PHP Question

PHP private variable is 'undefined' though it is defined

I've been toying with a RuneScape hiscore image creator. People tend to use these for signatures on their profiles on forums.

While reworking some of the code, I broke it. I'm getting:


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


However, the variable isn't even on line 8 (I assume that's something to do with it trimming white space).

Here is my User.php file

<?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;
}
}
?>


I was getting errors with the $names but that was because I wasn't using global $names in the functions.

Answer

You're using the wrong syntax.

Use $this->variableName not $this->$variableName

i.e. change return $this->$exp[0]; to return $this->exp[0];

Comments