-1

Why this code print "AA" if I give same name of my class name my function into my class.

class A{

     public function a() {
        echo 'A';
    }
}

$a = new A();
$a->a(); // AA

Thanks !

Aina
  • 28
  • 1
  • 3

2 Answers2

0

This happens because, each of your lines call a(), as it's named after the Class, it's used as a constructor function, for the class A.

Usually you'd use the __construct-function, that would act as constructor, but as no function is called __construct, the function named after the class, will be called. So actually your output looks like:

$a = new A(); // A
$a->a(); // A

Which accumulates into outputting AA

For backwards compatibility with PHP 3 and 4, if PHP cannot find a __construct() function for a given class, and the class did not inherit one from a parent class, it will search for the old-style constructor function, by the name of the class.

http://php.net/manual/en/language.oop5.decon.php

Frederik Spang
  • 3,379
  • 1
  • 25
  • 43
-1

Constructor call automatically as soon as you declare function a()

  • Welcome to StackOverflow, and thank you for taking the time to help answering questions! Generally when answering questions, you want to explain why a given method does not work, as well as include an alternative that helps the author in the right direction. I'd recommend reading [How do I write a good answer](http://stackoverflow.com/help/how-to-answer). – CmdrSharp Nov 06 '16 at 14:46