6

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).

8
  • I don't think it's a bug while $this is a reference to the calling object (ChildClass in your example) that has method childMethod so script works. I'd say this is technically possible but bad practice.
    – Leri
    Jan 29, 2013 at 13:07
  • @PLB But what if subclass didn't happen to implement a childMethod()? There's nothing in BaseClass that forces ChildClass to implement it.
    – GordonM
    Jan 29, 2013 at 13:09
  • Probably, trigger Call to undefined method
    – Leri
    Jan 29, 2013 at 13:09
  • 1
    This would be a compile-time error in a static-typed language like C#. But this is PHP...
    – Palantir
    Jan 29, 2013 at 13:10
  • 1
    @GordonM I agree it's not expected behavior but it can't be a bug since $this refers to an object not a class itself. There's self that refers to current class.
    – Leri
    Jan 29, 2013 at 13:17

3 Answers 3

8

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

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.

2
  • The problem with that, to me at least, is that it means you can write a base class and assume that all its subclasses implement some functionality without actually explicitly stating that fact. Suppose I had an OtherChildClass extends BaseClass and didn't implement a childMethod() in it, or implemented a private childMethod(). There's nothing stopping me from doing that because I've not put an abstract childMethod() in the base class
    – GordonM
    Jan 29, 2013 at 13:13
  • Yes, that's right. There is no pre-run check in PHP, so you will always have runtime errors in PHP if you didn't code properly. There might still be some IDEs for PHP, that would remark such error. Jan 29, 2013 at 13:17
0

PHP is very dynamic language and it allows you to use polymorphism without inheritance. In this case, it simply looks for method 'childMethod' in run-time and since it exists, it will call it. How you got that method there is not important. You could also generate that method dynamicaly with __call magic method. You can never do this in C++ or Java, but in languages like PHP or Javascript it is all fine and it gives you a lot more options.

1
  • 2
    While you are basically correct, PHP is in fact the ugly offspring of a Swan and a Cat, both may be beautiful in their own way, but the combination is just an ugly thing with beaks and claws that stabs you in the back
    – dualed
    Jan 29, 2013 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.