• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Quick (Stupid) expression about variable scope in PHP

kyzen

Golden Member
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? 🙂




 
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';
}
 
the "$this" bit is what I totally missed, thanks a ton!

The public/private is also good to know 🙂
 
Back
Top