Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP superclass calling subclass methods without knowing about them?

Whilst trying to debug some PHP classes, I ran into some behaviour which is, to my mind, really weird.

I've constructed a demonstration of the behaviour below:

class BaseClass {
   public function baseMethod () {
      echo (implode (' ', $this -> childMethod ()) . PHP_EOL);
   }
}

class ChildClass extends BaseClass {
   protected function childMethod () {
      return array ('What', 'The', 'Actual', 'Fork!');
   }
}

$a = new ChildClass ();
$a -> baseMethod ();

Now, to my mind, the base class should not be able to make any assumptions about the subclass at all, except for the ones it enforces for the subclass by declaring (or inheriting) abstract methods, or by implementing an interface. However, the above code actually outputs a string and doesn't throw any errors!

What The Actual Fork!

This seems like broken behaviour to me. Unless the base class declares abstract protected function childMethod();, it should not be able to call it, should it?

I've been scouring the internet to try and find something that demonstrates that this is expected behaviour. So far all I've managed to find is the following from PHP's manual:

Visibility from other objects

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects

So is the behaviour I'm witnessing here correct or is this a bug in PHP? It's certainly not behaviour I'd rely on because it seems wrong to me.

FYI, the problem we found in the actual code was that the subclass declared a private method that the superclass was trying to call. The superclass didn't declare the method abstract (and if it had done it would have had to be at least protected).

like image 970
GordonM Avatar asked Jan 29 '13 12:01

GordonM


People also ask

Can a superclass call the methods of a subclass?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

How do you call a method from a sub class?

Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.

How do you call method of subclass from parent class?

Yes its possible to call sub class methods using super class by type casting to sub class object . By type casting super class object to sub class object we can access all corresponding sub class and all super class methods on that reference.


2 Answers

Now, to my mind, the base class should not be able to make any assumptions about the subclass at all, except for the ones it enforces for the subclass by declaring (or inheriting) abstract methods, or by implementing an interface.

That's how things work in statically typed languages. In PHP (and many others) you are free to call any method on any value (it need not even be an object). If the call does not make sense, you get a runtime error.

Of course it's a good idea to declare the method if you expect derived classes to implement it; this is simply good practice. Additionally, many well-known PHP IDEs will detect such an omission and flag the call to bring it to your attention exactly because the compiler cannot.

This seems like broken behaviour to me. Unless the base class declares abstract protected function childMethod();, it should not be able to call it, should it?

It should, as explained above. If you find this behavior undesirable, PHP is not the language you should be using.

Aside: In a closely related note, you might also find it counter-intuitive that a base class can access protected members defined in a derived class without any trouble. This is documented. In fact it is exactly what happens in your example, but I mention it specifically because it's a different kind of counter-intuitive (your example would also be as puzzling if the method were public).

Consider the endless list of constructs that PHP allows which also "should not be possible" from a statically typed perspective, which include:

// #1
$varName = 'foo';

// How do you know $object has a property named "foo"?
// How do you know that "foo" is a valid property name in the first place?
// How do you know that $object is an object to begin with?
echo $object->$varName;

// #2
$object = new SomeObject;
$methodName = 'someMethod';

// it's practically impossible to reason about this before runtime
call_user_func(array($object, $methodName));
like image 166
Jon Avatar answered Oct 20 '22 14:10

Jon


It isn't a bug. It should work like that. Let me try to comment the method invocation:

class BaseClass {
   public function baseMethod () {
      echo (implode (' ', $this -> childMethod ()) . PHP_EOL);
   }
}

class ChildClass extends BaseClass {
   protected function childMethod () {
      return array ('What', 'The', 'Actual', 'Fork!');
   }
}

/****/

$a = new ChildClass ();
/** $a is now instance of ChildClass, that is a sublass of BaseClass
 *  so the Object $a has 2 methods: baseMethod() inherited from BaseClass and childMethod() from ChildClass.
 */

$a -> baseMethod ();
/** now you're calling $a->baseMethod(), which will do a method call on $this->childMethod(). 
 *  As $this is refering $a here, $a has indeed a method named childMethod(), that will be called.
 */

What you're wondering about is the visibility with protected. But as $a is type of ChildClass, the protected method is surely visibile to it and to the inherited baseMethod(). That should be equal in every OOP language.

The bad part of your code is the assumption inside baseMethod() of calling a childMethod(). That will always conclude with an error, if there is no such method. OOP languages like Java would throw a compilation error here, but PHP won't, as there is no pre-run compiler in PHP. If you change the initialization from e.g. $a = new ChildClass (); to $a = new BaseClass ();, you will get a runtime error in PHP, too.

like image 43
ConcurrentHashMap Avatar answered Oct 20 '22 15:10

ConcurrentHashMap