Quick (Stupid) expression about variable scope in PHP

kyzen

Golden Member
Oct 4, 2005
1,557
0
0
www.chrispiekarz.com
I have a simple class in PHP that I want to hold some "global" variables if you will, so that I can use them immediately with a default value.

However, the values I set don't seem to stick.

Can anybody help me out here, and let me know what I'm doing wrong? I've tried a constructor (that I possibly did wrong), or just setting the variable value when I create it. Neither work.

Any idea on where I'm being an idiot here? :)




 

NiKeFiDO

Diamond Member
May 21, 2004
3,901
1
76
1) Are you using PHP5 or php4? (This determines the use of "var" and your constructor)

If php4, use "var" and make your constructor function the same as your class.

If php5, set your variables to "public" "private" or "protected" and don't use "var"

class myclass {
var $something;

function myclass() {
$this->something = 'yay something';
}
}

vs

class myclass {
public $something;

public function __construct() {
$this->something = 'yay something';
}
}
2) To access the variables you have "var"ed, you need to use the "$this" operator. (as you may note in the examples above)

function __construct() {
$this->ItemName = "test";
$this->ItemCategory = 'category';
}