Jump to content


Photo

Class problems (crazy variable)


  • Please log in to reply
2 replies to this topic

#1 XiaoRulez

XiaoRulez
  • Members
  • PipPip
  • Member
  • 10 posts

Posted 05 July 2006 - 10:41 AM

This is a class i wrote and it's giving me crap -_- it should be counting up but the thing is, it's just staying at 0 and not changing, or any changes made goes back to 0 again ($items variable)... (think it's got to do with php thinking that $itams = 0, the 0 is seen to be NULL?)

can anyone spot any mistakes?

class lists {
	private $item = array();
	private $items;

	function lists() {
		$items = 0;
	}

	function push_back($var) {
		$item[$items] = $var;
		$items++;
		echo '[New Item] Current Items: '.$items.'<br>'."\n";
	}

	function push_front($var) {
		$temp = array();
		$temp[0] = $null;
		$count = 0;
		foreach($item as $i_one) {
			$count++;
			$temp[$count] = $i_one;
		}
		$item = $temp;
		$items++;
	}

	function pop_back() {
		$temp = $item[$items-1];
		$item[$items-1] == $null;
		$items--;
		return $temp;
	}

	function pop_front() {
		$temp = $item[0];
		$temp2;
		$count = 0;
		foreach($item as $i_one) {
			$count++;
			if ($count != 1) $temp2[$count] = $i_one;
		}
		$temp2[$count] = $null;
		$item = $temp2;
		$items--;
		return $temp;
	}

	function size_of() {
		return $items;
	}

	function erase($loc) {
		if ($loc > $items || $loc < 0) return $false;
		else {
			$temp = $item[0];
			$temp2;
			$count = $loc;
			foreach($item as $i_one) {
				$count++;
				if ($count != 1) $temp2[$count] = $i_one;
			}
			$temp2[$count] = $null;
			$item = $temp2;
			$items--;
			return $true;
		}
	}

	function at($loc) {
		return $item[$loc];
	}
}

$a = &new lists();

function new_a($name) {
	global $a;
	$size = $a->size_of();
	$a->push_back($name);
}
$name2 = "who";
new_a($name2);
new_a($name2);
new_a($name2);

[New Item] Current Items: 1
[New Item] Current Items: 1
[New Item] Current Items: 1



#2 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 05 July 2006 - 10:57 AM

The problem is you are not using the variables you have defined in your class. In order to refer to the class variables you'll need to use $this->varname in order access the variables within the class. Otherwise the variables you use within a function will not eference variables outside of the function.

So when you use $item or $items you'll want to use $this->item and $this->items with in your methods (the functions).

In order to understand this behaviour you might want to read up on variable-scope

#3 XiaoRulez

XiaoRulez
  • Members
  • PipPip
  • Member
  • 10 posts

Posted 06 July 2006 - 05:49 AM

:S i'm kinda used to C++ any we don't need to use that all the time :P

thanks a heap.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users