Class variables, scope resolution operator and different versions of PHP

假如想象 提交于 2020-01-11 13:24:32

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/539677/class-variables-scope-resolution-operator-and-different-versions-of-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!