Re: An overloading question [message #174496 is a reply to message #174495] |
Tue, 14 June 2011 23:43 |
sheldonlg
Messages: 166 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 6/14/2011 7:12 PM, Jerry Stuckle wrote:
> On 6/14/2011 6:27 PM, sheldonlg wrote:
>> On 6/14/2011 2:32 PM, Denis McMahon wrote:
>>> On Tue, 14 Jun 2011 12:49:11 -0400, sheldonlg wrote:
>>>
>>>> I have a problem that I am wrestling with that should be so obvious and
>>>> easy -- but it isn't. I have a base class that has a method that calls
>>>> another method in the base class with $this->thatOtherMethod. I have
>>>> another class that extends the base class and I want to have
>>>> thatOtherMethod in the extended class override the one in the base
>>>> class. The calling method in the base class is called using and
>>>> instance of the extended class pointing to that method.
>>>>
>>>> Simply, here is an example:
>>>>
>>>> A.class.php
>>>> --------------------------
>>>> <?php
>>>> abstract class A {
>>>> public function b() {
>>>> $this->a();
>>>> }
>>>> protected function a() {
>>>> print 'In class A';
>>>> }
>>>> }
>>>> ?>
>>>>
>>>> B.class.php
>>>> ---------------------------
>>>> <?php
>>>> include_once 'A.class.php';
>>>> class B extends A {
>>>> public function a() {
>>>> print 'In class B';
>>>> }
>>>> }
>>>> ?>
>>>>
>>>> c.php
>>>> ----------------------------
>>>> <?php
>>>> include 'B.class.php';
>>>> $x = new B();
>>>> $x->b();
>>>> ?>
>>>> ----------------------------
>>>>
>>>> I want it to print out "In class B", but it prints out "In class A".
>>>>
>>>> I have looked over Google quite a bit and found nothing that helped. I
>>>> have tried making the methods public, protected, keep them both the
>>>> same
>>>> access, etc. and have had no luck. Suggestions?
>>>
> Unfortunately, PHP doesn't really implement OO constructs very well - in
> fact they to a pretty piss poor job of it. One of the problems is with
> virtual functions, as you found. A good OO language would work like you
> want, but PHP doesn't - the constructor for A will, in this case, only
> call a function in A. In C++, Smalltalk, Java and most other OO
> languages, you could define y() as virtual and the constructor for A
> would call the function y() in B.
I could define the method in A as abstract (and the class). It would
then require that it be implemented in B. However, I am not the only
application using A, and so doing that would require all the other apps
to also implement it in an extended class. That is a no-no and is one
of the reasons for using B in the first place.
>
> But if you created a constructor in B properly, it should call B:y().
I did create a constructor in B properly.
> I'd suggest checking your code again - you might have made a mistake.
>
No mistakes that I could find.
--
Shelly
|
|
|