【问题标题】:Is instantiation required for function overriding? [duplicate]函数重写是否需要实例化? [复制]
【发布时间】:2012-10-04 13:33:55
【问题描述】:

可能重复:
What exactly is late-static binding in PHP?

在这个例子中,PHP 将打印“NO”而不是“YES”,这与我的预期相反。

如果我删除function c() 上的static,将self:: 替换为$this-> 并执行$e = new B; $e->c();,一切都会奏效。

这是否意味着需要实例化才能使父类中的函数调用继承类中的覆盖函数?

(附带问题:这是 PHP 的怪癖,还是这种逻辑也适用于大多数其他编程语言?如果是,其背后的基本原理是什么?)

class A {
  static function c() {
    self::d();
  }
  static function d() {
    echo "NO :(\n";
  }
}

class B extends A {
  static function d() {
    echo "YES :)\n";
  }
}

B::c();

【问题讨论】:

  • 不是self::d(),而是static::d()

标签: php oop


【解决方案1】:

您需要使用static 关键字而不是self$this

<?php

class A {
    static function c() {
        static::d();
    }
    static function d() {
        echo "NO :(\n";
    }
}

class B extends A {
     static function d() {
         echo "YES :)\n";
     }
}

B::c();

// YES :)

这种行为称为Late Static Bindings

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    相关资源
    最近更新 更多