The following code outputs 10
. Why is that?
<?php
class a{
var $c;
public function a(){
$this->c=10;
}
}
class b extends a{
public function print_a(){
print $this->c;
}
}
$b=new b;
$b->print_a();
Because public function a()
is a constructor.
For backwards compatibility, if PHP 5 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.
see more at PHP constructor manual
In older versions of PHP public function a
is treated as class a
constructor. Because there is no constructor in class b
, class a
constructor is called and $c
is set to 10;
Well you actually named your function the samename as the class, this is an implicit constructor. So in short it's the same as __construct()
.
In OOP you have to keep in mind, that if you extend a class it's parent constructor is implicitly called when you create a new instance unless you explicitly override the constructor.
function a()
?function aa()
would make it function properly. @Oliboy50b()
) makes the outputnull
.