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 !
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 !
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.
Constructor call automatically as soon as you declare function a()