How can I set a global variable in this class? I have tried this:
class myClass
{
$test = "The Test Worked!";
function example()
{
echo $test;
}
function example2()
{
echo $test." again";
}
}
Which failed to load the page completely citing a 500 error. Next I tried this one:
class myClass
{
public $test = "The Test Worked!";
function example()
{
echo $test;
}
function example2()
{
echo $test." again";
}
}
But when I printed both of these, all I see is " again" Sorry for such a simple question!
Thanks!
this variable can be accessed like this
echo $this->test;
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With