Variable Scope Within PHP Class?

This variable can be accessed like this echo $this->test.

Thank you! It worked! – Pete Herbert Penito Dec 7 '10 at 3:30.

Class Foo { public $bar = 'bar'; function baz() { $bar; // refers to local variable inside function, currently undefined $this->bar; // refers to property $bar of $this object, // i.e. The value 'bar' } } $foo = new Foo(); $foo->bar; // refers to property $bar of object $foo, i.e. The value 'bar' Please start reading here: php.net/manual/en/language.oop5.basic.php.

If you want an instance variable (preserved only for that instance of the class), use: $this->test (as another answer suggested. ) If you want a "class" variable, prefix it with the "static" keyword like this: The class variable is different than the instance variable in that all object instances created from the class will share the same variable. (Note to access class variables, use the Class Name, or 'self' followed by '::') class myClass { public static $test = "The Test Worked!"; function example() { echo self::$test; } function example2() { echo self::$test.

" again"; } } Finally if you want a true constant (unchangeable), use 'const' in front (again access it with 'self' plus '::' plus the name of the constant (although this time omit the '$'): class myClass { const test = "The Test Worked! "; function example() { echo self::test; } function example2() { echo self::test." again"; } }.

There are actually two ways to access a variable or function in a class from either within the class or outside it, if they request item is public (or in some cases protected) class myClass { public $test = "The Test Worked! "; function example() { echo $this->test; // or with the scope resolution operator echo myClass::test; } function example2() { echo $this->test. " again"; // or with the scope resolution operator echo myClass::test." again"; } }.

In example2 there, doesn't it need to be echo $this->test. " again";? – Pete Herbert Penito Dec 7 '10 at 3:51 correct, I missed adding 'this' to that statement, updated... – Patrick Dec 7 '10 at 16:48.

Try adding $this to the front of your variables; you could change the second example to class myClass { public $test = "The Test Worked! "; function example() { echo $this->test; } function example2(){ echo $this->test. " again"; } }.

Which failed to load the page completely citing a 500 error. But when I printed both of these, all I see is " again" Sorry for such a simple question!

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions