Bug #37854 [Com]: Type Hinting with derived classes and interfaces not working

From: Date: Fri, 20 Apr 2012 10:39:54 +0000
Subject: Bug #37854 [Com]: Type Hinting with derived classes and interfaces not working
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-169790@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=37854&edit=1

 ID:                 37854
 Comment by:         kabanovdmitry at gmail dot com
 Reported by:        spam at codeword dot net
 Summary:            Type Hinting with derived classes and interfaces not
                     working
 Status:             Not a bug
 Type:               Bug
 Package:            Class/Object related
 Operating System:   *
 PHP Version:        *
 Block user comment: N
 Private report:     N

 New Comment:

Why then does PHP allow to narrow argument's type in subclass which extends base 
class?

This seems odd, because this violates Liskov Substitution Principle.


Previous Comments:
------------------------------------------------------------------------
[2006-06-19 22:21:23] helly@php.net

Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to
report
a bug at http://bugs.php.net/how-to-report.php

First we don't allow changesin the typhints in derived classes/implementing classes. Second you
need to learn inheritance rules again. Your code would break is-a relation.

------------------------------------------------------------------------
[2006-06-19 22:11:34] spam at codeword dot net

Description:
------------
When adding type hinting to an interface then implementing that interface using a derived class, the
script compiler does not seem to recognise that the implemented type hint is derived from the
interfaces type hint.  I hope that makes sense.  The code below may be more clear.

Reproduce code:
---------------
<?php
interface MyInterface{public function test(ClassA $object);}
class MyClass implements myInterface{
  public function test(ClassB $object){// should work but does not
    echo $object->x;
  }
}
class ClassA {public$x = "Class is ClassA";  }
class ClassB extends ClassA{  public $x = "Class is ClassB";}
$myclass = new MyClass;
$a = new ClassA;
$b = new ClassB;
$myclass->test($b);
$myclass->test($a);
?>

Expected result:
----------------
Class is ClassB
Fatal error: Argument 1 passed to MyClass::test() must be an instance of ClassB, called in
typeHintTest.php on line 14 and defined in typeHintTest.php on line 4

Actual result:
--------------
Fatal error: Declaration of MyClass::test() must be compatible with that of MyInterface::test() in
typeHintTest.php on line 3


------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=37854&edit=1


Thread (5 messages)

« previous php.bugs (#169790) next »