|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2003-02-17 11:38 UTC] goba@php.net
In this example, the printStr() method becomes the constructor of the printStr class, while I think it should not be working this way... I hope this is not by design ;)
class String
{
function printStr($string)
{
print $string;
}
}
class printStr extends String {}
$ps = new printStr("abc");
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 11:00:02 2025 UTC |
No, no and no. Excerpts: |In PHP 4, a function becomes a constructor, |when it has the same name as the class it |is defined in" In my example, the function printStr is not defined in class printStr, so it should not become a constructor according to this statament. Another example at the bottom of the page you mentioned: |class A |{ | function A() | { | echo "I am the constructor of A.<br>\n"; | } | | function B() | { | echo "I am a regular function named B in class | A.<br>\n"; | echo "I am not a constructor in A.<br>\n"; | } |} | |class B extends A |{ | function C() | { | echo "I am a regular function.<br>\n"; | } |} | |// This will call B() as a constructor. |$b = new B; | |In PHP 3, the function B() in class A will suddenly become |a constructor in class B, although it was never intended to |be. The rule in PHP 3 is: 'A constructor is a function of |the same name as the class.'. PHP 3 does not care if the |function is being defined in class B, or if it has been |inherited. | |This is fixed in PHP 4 by modifying the rule to: 'A |constructor is a function of the same name as the class |it is being defined in.'. Thus in PHP 4, the class B |would have no constructor function of its own and the |constructor of the base class would have been called, |printing 'I am the constructor of A.<br>'. The above example says, that the B() method becomes a constructor in PHP 3, but *not* in PHP 4, as there is no constructor defined for class B itself. Therefore it inherits the base classes constructor, which exists in the manual's example. In my case, there is no constructor in the base class. Therefore it should not call any method, as the text suggests. So this is not a documented behaviour. In fact it is documented, that it should not work this way in PHP 4, but only in PHP 3...