To clear up that confusion about public and public static access in PHP

This post is more than 18 months old. Since technology changes to rapidly, this content may be out of date (but that's not always the case). Please remember to verify any technical or programming information with the current release.

Apparently, a few programmers I know have been getting confused about access of public, public static variables in PHP classes. I’ve written this example code with the following comments to explain what will work - and what won’t.

class TEST
  /** public variable **/
  public $pubvar = 'pubvar';
  /** static public variable **/
  public static $pubvarstatic = 'pubvarstatic';
  public function __construct()
    /** this works **/
    /** this also works **/
    /** this would not - no error **/
  public static function statictest()
    /** this works - static accessing a static **/
     * this does not work - static has no business accessing a non static class var
     * generates error:
     * Fatal error:  Access to undeclared static property:  TEST::$pubvar
print "<pre>";
/** for testing __construct() **/
new TEST;
/** this works - public static access **/
/** for testing static method statictest() **/

Return to All Posts