Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Scope Within PHP Class

Tags:

scope

php

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!

like image 398
Doug Molineux Avatar asked Dec 07 '10 03:12

Doug Molineux


2 Answers

this variable can be accessed like this

echo $this->test;
like image 66
Ish Avatar answered Sep 27 '22 21:09

Ish


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";
   }
}
like image 44
Matthew Mucklo Avatar answered Sep 27 '22 21:09

Matthew Mucklo