What is the difference between constructors in PHP4 & PHP5?
Top Questions
Constructors - PHP4 Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base class is being called, if it exists.
<?php
class Auto_Cart extends Cart {
function Auto_Cart() {
$this->add_item("10", 1);
}
}
?><?php
class Constructor_Cart extends Cart {
function Constructor_Cart($item = "10", $num = 1) {
$this->add_item ($item, $num);
}
}
// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;
// Shop for real...
$different_cart = new Constructor_Cart("20", 17);
?><?php
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
{
}
// This will call B() as a constructor
$b = new B;
?>Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. using new unified constructors
<?php
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}
$obj = new BaseClass();
$obj = new SubClass();
?>Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
Post new comment