-3

Possible Duplicate:
Why is my constructor still called even if the class and constructor case are different?

<?php
 abstract class foo {
  function foof() {
   echo "Hello, I'm foo :)";
  }
 }

 class foo2 extends foo {
  function foo2f() {
   $this->foof();
  }
 }

 class foo3 extends foo2 {
  function foo3f() {
   $this->foo2f();
  }
 }

 $x = new foo3;
 $x->foo3f();
?>

This code outputs "Hello, I'm foo :)" (as expected) but when I change code to something like this: http://pastebin.com/wNeyikpq

<?php
abstract class foo {
 function fooing() {
  echo "Hello, I'm foo :)";
 }
}

class foo2 extends foo {
 function foo2() {
  $this->fooing();
 }
}

class foo3 extends foo2 {
 function foo3() {
  $this->foo2();
 }
}

$x = new foo3;
$x->foo3();
?>

PHP prints:

Hello, I'm foo :)Hello, I'm foo :)

Why? Is it a bug?

Community
  • 1
  • 1
kiler129
  • 1,063
  • 2
  • 11
  • 21
  • I put second code on pastebin due to stackoverflow bug (lol) - http://cl.ly/3J352B14073S15282O2s – kiler129 Dec 02 '11 at 22:04
  • 3
    This is not a bug in PHP, and that's not a bug in StackOverflow. – gen_Eric Dec 02 '11 at 22:14
  • 4
    In general, you're going to draw the ire of people here if your question assumes (even if you just mention it in passing) that there's a bug in the language you're using, and not in the code you've written. – jwheron Dec 02 '11 at 22:18

2 Answers2

8

Because you are calling the foo2 two times, function foo2() in foo2 it's a constructor.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • 1
    +1 This is correct. See [Constructors and Destructors](http://php.net/manual/language.oop5.decon.php). –  Dec 02 '11 at 22:06
  • 6
    _Note for passersby_: A method of the same name as its class is treated as a constructor for backward compatibility with PHP4. Starting in PHP5, you should use the [`__construct()`](http://php.net/manual/en/language.oop5.decon.php) method instead. – Wiseguy Dec 02 '11 at 22:07
4

The correct answer is not that function foo2() in foo2 it's a constructor, although it's true that it's a constructor.

The answer is that foo3() is the constructor called in new foo3(). This constructor calls the method foo2().

Actually the constructor of foo2 newer is called since foo3 has not a call to his parent constructor.


Because you are calling foo3() two times, function foo3() in foo3 is a constructor Docs:

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class.

First call:

$x = new foo3;

Second call:

$x->foo3f();

Give foo3 a real constructor and you're fine:

class foo3 extends foo2 {
 function __construct() {};
 function foo3() {
  $this->foo2();
 }
}
hakre
  • 193,403
  • 52
  • 435
  • 836
macjohn
  • 1,755
  • 14
  • 18