Tuesday, March 15, 2011

Class variables, scope resolution operator and different versions of PHP

I tried the following code in codepad.org:

class test { 
  const TEST = 'testing 123';
  function test () {
    $testing = 'TEST';
    echo self::$testing;
  }
} 
$class = new test;

And it returned with:

1
2 Fatal error: Access to undeclared static property:  test::$testing on line 6

I want to know whether referencing a class constant with a variable would work on my server at home which runs php 5.2.9 whereas codepad uses 5.2.5 . What are changes in class variables with each version of PHP?

From stackoverflow
  • The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class.

    The variable you define in the function test ($testing) is not a static or constant, therefore the scope resolution operator doesn't apply.

    class test { 
      const TEST = 'testing 123';
      function test () {
        $testing = 'TEST';
        echo $testing;
      }
    } 
    
    $class = new test;
    

    Or just access the constant outside the class:

    test::TEST;
    

    It should work on your server at home if used correctly. In regards to the OOP changes from PHP4 to PHP5, the php documentation may be useful. Although just off the top of my head, I would say that PHP5's main changes as they relate to class variables would be their visibility, static's and constants. All of which are covered on the documentation link provided.

0 comments:

Post a Comment