【问题标题】:Class variables, scope resolution operator and different versions of PHP类变量、范围解析运算符和不同版本的 PHP
【发布时间】:2010-10-07 01:59:21
【问题描述】:

我在 codepad.org 中尝试了以下代码:

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

它返回:

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

我想知道使用变量引用类常量是否可以在我家运行 php 5.2.9 而 codepad 使用 5.2.5 的服务器上工作。 各个版本的 PHP 对类变量有何变化?

【问题讨论】:

    标签: php class-variables


    【解决方案1】:

    范围解析运算符(也 称为 Paamayim Nekudotayim) 或在 更简单的术语,双冒号,是 允许访问静态的令牌, 常量和被覆盖的成员或 类的方法。

    您在函数 test ($testing) 中定义的变量不是静态或常量,因此范围解析运算符不适用。

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

    或者只是访问类外的常量:

    test::TEST;
    

    如果使用正确,它应该可以在您家中的服务器上运行。关于从 PHP4 到 PHP5 的 OOP 更改,php documentation 可能有用。虽然只是在我的脑海中,但我会说 PHP5 与类变量相关的主要变化是它们的可见性、静态和常量。所有这些都包含在提供的文档链接中。

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 2012-04-20
      • 2018-04-24
      • 2011-11-04
      • 2015-09-14
      相关资源
      最近更新 更多