The child constant called is not available in the static function in the parent

I have a static function in a class that needs to be called from several child classes. I need a constant from the calling child class that will be available in this function. To make these constants available elsewhere, the child classes have a function that returns the value of this constant (php 5.2.9).

However, when in the parent class I cannot access this constant, not the function or directly. Is this possible in php 5.2.9 or do I need to pass it as an argument?

This is a simple version of the code:

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(); 

Edit: created error:

  • Call the undefined method ParentClass :: show_const () (for a function)
  • Undefined class constant 'SOME_CONST' (using self :: SOME_CONST)
+6
object php class parent-child self
source share
2 answers

Unfortunately, what you are trying to do will not work until 5.3. The problem here is early static binding to late static binding. The self keyword is bound earlier, so it only looks in the class where it is used to resolve characters. The magic constant __CLASS__ or the get_class() function will not work either, it also does early static binding. For this reason, PHP 5.3 decoded the static to indicate late binding when used as static::some_method() .

So in 5.3 this would work:

 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(); 
+13
source share

You need to make ChildClass an extension of the parent class:

 class ChildClass extends ParentClass { 

Edit:

You are trying to refer to a constant and a method in a child class from a parent class that does not know that the child class "constant" exists. This is a question of scale. A child can refer to parent methods and constants, but not vice versa.

+2
source share

All Articles