父级中的静态函数中称为子级常量不可用

jer*_*oen 6 php class object self parent-child

我在一个类中有一个静态函数,需要从几个子类中调用.我需要一个来自调用子类的常量才能在该函数中使用.为了让这些常量在其他地方可用,子类有一个返回该常量值的函数(php 5.2.9).

但是,在父类中,我似乎无法访问该常量,不能直接访问该函数.甚至可以在php 5.2.9中使用,还是我需要将其作为参数传递?

这是代码的简单版本:

abstract class ParentClass {
    static function DoSomething() {
        $not_working = self::show_const();
        $not_working_either = self::SOME_CONST;

        return 'working';
    }
}

class ChildClass extends ParentClass {
    const SOME_CONST = 'some string';

    function show_const() {
        return self::SOME_CONST;
    }
}

$result = ChildClass::DoSomething();
Run Code Online (Sandbox Code Playgroud)

编辑:生成的错误是:

  • 调用未定义的方法ParentClass :: show_const()(用于函数)
  • 未定义的类常量'SOME_CONST'(使用self :: SOME_CONST)

fre*_*sch 13

不幸的是,你要做的是在5.3之前不会工作.这里的问题是早期静态绑定与后期静态绑定.该self关键字的早期结合,所以它看起来只是在用它来解析符号类.魔术常量__CLASS__或函数get_class()也不起作用,这些也可以进行早期静态绑定.出于这个原因,PHP 5.3将static关键字扩展为使用时的后期绑定static::some_method().

所以在5.3这将工作:

abstract class ParentClass {
  public static function DoSomething() {
    return static::show_const();
    // also, you could just do
    //return static::SOME_CONST;
  }
}

class ChildClass extends ParentClass {
  const SOME_CONST = 'some string';
  public static function show_const() {
    return self::SOME_CONST;
  }
}

$result = ChildClass::DoSomething();
Run Code Online (Sandbox Code Playgroud)