|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2007-03-21 09:38 UTC] prometheus__0 at hotmail dot com
Description:
------------
(1) It is not possible to make inherited functions more private, which seems like a bug to me but
(2) it is possible to make inherited functions more public, which shouldn't be possible, afaik.
The example code causes the fatal (1)
if you change
protected function __construct()
to
public function __construct()
from class b
and
public function __construct(){
to
protected function __construct(){
from class a
it works (2)
since i'm not an expert in oop i tried the same example in java and it works the complete opposite way (the b functions can be more private but not more public)
and in C++ it's the same
i know bug report http://bugs.php.net/bug.php?id=34237 but it considers point (2)
point (1) is still a bug in my opinion
Reproduce code:
---------------
<?php
class a{
public function __construct(){
print("public construct\n");
}
}
class b extends a{
protected function __construct(){
print("protected construct\n");
}
public static function getInstance(){
return new b();
}
}
$b = b::getInstance();
?>
Expected result:
----------------
protected construct
Actual result:
--------------
Fatal error: Access level to b::__construct() must be public (as in class a) in PHPDocument2 on line 16
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Nov 04 22:00:01 2025 UTC |
Same "problem". class A{ public function __construct(){} } class B extends A { protected function __construct(){} } Please, can you tell us a reason why we can't put an private/protected access to B's constructor if A's constructor is public ? Is there any logical reason to this ? Thanks.@rasmus: Then why is there a strict warning regarding the compatibility of method signatures for this code: -------------- class Foo { public function test() { } } class Bar extends Foo { public function test(ArrayObject $arrayObj, $number = 0) { /* do stuff with $arrayObj and $number */ } } --------------- and not for this one: --------------- class Foo { public function __construct() { } } class Bar extends Foo { public function __construct(ArrayObject $arrayObj, $number = 0) { /* do stuff with $arrayObj and $number */ } } ------------ No, as stated here : - http://stackoverflow.com/questions/5490824/should-constructors-comply-with-the-liskov-substitution-principle - and here: http://ralphschindler.com/2012/03/09/php-constructor-best-practices-and-the-prototype-pattern, the LSP does not apply to constructors for several reasons: - When you call the constructor, you know whether you're using the type or one of its subtypes. - You can't apply the LSP to an object that does not exist yet. I think this is a design flaw. Not "massive", but a design flaw indeed.