代码之家  ›  专栏  ›  技术社区  ›  fresskoma

从PHP5中的抽象方法访问类常量

  •  1
  • fresskoma  · 技术社区  · 14 年前

    我试图得到一个扩展类的常数的值,但是在一个抽象类的方法中。这样地:

        abstract class Foo {
            public function method() {
                echo self::constant;
            }
        }
    
        class Bar extends Foo {
            const constant = "I am a constant";
        }
    
        $bar = new Bar();
        $bar->method();
    

    但是,这会导致致命错误。有没有办法做到这一点?

    1 回复  |  直到 12 年前
        1
  •  3
  •   Morfildur    14 年前

    abstract class Foo {
      protected abstract function getBar();
    
      public function method() {
        return $this->getBar();
      }
    }
    
    class Bar extends Foo {
      protected function getBar() {
        return "bar";
      }
    }
    
        2
  •  3
  •   Daniel Flynn    4 年前

    这可以使用PHP5.3中引入的后期静态绑定关键字实现

    基本上, self 指编写代码的当前类,但 static 指运行代码的类。

    我们可以将您的代码段重写为:

    abstract class Foo {
        public function method() {
            echo static::constant;    // Note the static keyword here
        }
    }
    
    class Bar extends Foo {
        const constant = "I am a constant";
    }
    
    $bar = new Bar();
    $bar->method();
    

    然而,这种编码模式是肮脏的,您可能应该在父类和子类之间引入一个受保护的api来来回传递此类信息。

    因此,从代码组织的角度来看,我更倾向于 提出