【问题标题】:Does static keyword have any effect on constants?static 关键字对常量有影响吗?
【发布时间】:2012-07-25 19:48:34
【问题描述】:
class A{
  const FOO = 1;
}

class B extends A{

  const FOO = 5;

  function foo(){
    print self::FOO;
    print static::FOO;
  }
}

$b = new B;
$b->foo();

在这两种情况下都会打印 5。

那么在常量上使用 static 和 self 没有区别吗?

【问题讨论】:

  • 我收到Parse error: syntax error, unexpected T_STATIC。你有错误报告吗?
  • @WesleyMurch 显然使用static 作为范围仅适用于 PHP 5.3 及更高版本。你有低版本的PHP吗?这可能是错误的根源。
  • 我在codepad.org上运行它,看起来他们的版本是5.2

标签: php class static constants


【解决方案1】:

在Late Static Binding 的上下文中存在差异。

考虑这段代码:

<?php

class A {
    const FOO = 1;

    function bar() {
        print self::FOO;
        print "\n";
        print static::FOO;
    }
}

class B extends A {
    const FOO = 5;
}

$b = new B;
$b->bar();  // 1 5

如果你运行这段代码,输出将是:

1
5

引用self::FOO时,会打印1的值(尽管bar()在类B上被调用,但是当使用static关键字时,后期静态绑定生效并引用了使用 static 关键字时,FOO 常量来自 B 而不是 A。

这与 PHP 5.3 及更高版本有关。

【讨论】:

  • TX。我想我误解了后期静态绑定。看来它与从父类做子类的事情有关
  • 是的,一开始这很令人困惑,但基本上你是在正确的轨道上。如果调用是由派生对象进行的,则在父类中使用static 允许这些父类在运行时访问派生类的属性、常量和方法。虽然self::FOO 指的是A 类中的FOO,因为bar 是在A 中定义的,但static::FOO 可以引用B 类中的FOO,因为我们最终从@98765 中调用了bar()4@4@3 ,即使 bar() 是在 A 中定义的。
【解决方案2】:

在您的示例中,还不足以看出差异。但是,如果您有:

class Foo
{
  protected static $FooBar = 'Foo';

  public function FooBar()
  {
    echo "static::\$FooBar = " . static::$FooBar . PHP_EOL;
    echo "self::\$FooBar = " . self::$FooBar . PHP_EOL;
  }
}

class Bar extends Foo
{
  protected static $FooBar = 'Bar';
}

$bar = new Bar();
$bar->FooBar();

您会看到不同之处(范围和正在解析的实例 [inherited vs. base])

self, parent and static keywords

【讨论】:

    【解决方案3】:

    是的,有区别。在您的示例代码中,self 和 static 都引用了相同的 const FOO 声明。

    用户“drew010”发送的示例显示了差异。

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 2010-10-25
      相关资源
      最近更新 更多