Difference between revisions of "PHP OO problem"

From Organic Design wiki
m
m (The question)
Line 31: Line 31:
 
== The question ==
 
== The question ==
 
Is there a way to define a ''Bar::X'' method that calls ''Foo:X'' while maintaining the context of ''Bar'' (i.e. the value of ''self'' is "Bar" during execution of ''Foo::X''?
 
Is there a way to define a ''Bar::X'' method that calls ''Foo:X'' while maintaining the context of ''Bar'' (i.e. the value of ''self'' is "Bar" during execution of ''Foo::X''?
 +
 +
== Notes ==
 +
It seems to me from the documentation about [http://www.php.net/manual/en/function.forward-static-call.php forward_static_call] that the following definition for ''Bar::X'' should work, but instead yields a segmentation fault :-(
 +
{{code|<php>
 +
public static function X() {
 +
forward_static_call('Bar::X');
 +
}
 +
</php>}}

Revision as of 00:05, 30 July 2013

Take the following example class Foo which defines a static method called X that statically calls another of it's method's called Y using self::Y() as follows.

<php>

class Foo {

public static function X() { self::Y(); }

public static function Y() { echo( "This is Foo::Y" ); }

} </php>


Now lets say that Foo is part of a core library that we don't have commit access to and we want to make a modified version of the functionality via a sub-class of Foo called Bar which overrides the Y method as follows.

<php>

class Bar extends Foo {

public static function Y() { echo( "This is Bar::Y" ); }

} </php>

The problem

The Y method is only ever called via the self::Y statement in the X method, so when we call Bar::X() it's actually Foo::Y that executes, because X only ever executes within the context of Foo since we haven't overridden the X method with a definition in the Bar class.

The question

Is there a way to define a Bar::X method that calls Foo:X while maintaining the context of Bar (i.e. the value of self is "Bar" during execution of Foo::X?

Notes

It seems to me from the documentation about forward_static_call that the following definition for Bar::X should work, but instead yields a segmentation fault :-(

<php>

public static function X() { forward_static_call('Bar::X'); } </php>