Reputation: 1735
The parent class has a constructor like this:
function CD_Log( $id = false ) {
$this->__construct( $id );
}
function __construct( $id = false ) {
global $cd;
if ( !empty( $id ) ) {
$this->id = $id;
$this->populate();
}
}
In the extended Class, I want to save some of parent's var and child's var to a different place, also won't use the populate() function. Other than that, the child is constructed the same way as parent. Should I write a contructor for the child?
Upvotes: 0
Views: 168
Reputation: 19999
If you are following OOP as you are now, you should remove the global call for $cd, set this as a member var of either the parent or child.
Constructors, as I have seen them commonly used are normally called when you instantiate the object, not through another method of the same class, like the method CD_Log is doing.
For example:
$myCdObject = new MyCdClass(); // Automatically calls constructor
$myCdObject->Cd_Log($string);
With the above example you are ensure the CD_Log method is only dealing with log
logic. Unless you make CD_Log a static function, then you can instantiate the class within:
public static function CD_Log($id)
{
$myCdObject = MyCdClass(); // Automatically calls constructor
// Continue with `log` logic
}
To answer your question you probably want a constructor in the child class, which will call the parent constructor explicitly:
class parent
{
public function __construct($id)
{
$this->id = $id;
}
}
class child extends parent
{
public function __construct($id)
{
// Going to take advantage of shared logic
parent::__construct($id);
// Now lets do some child class specific stuff
}
}
Upvotes: 1
Reputation: 255115
If you need - you can override a constructor in child class. But keep in mind that in this case parent constructor will not be called automatically and you need to do that manually parent::_construct()
Upvotes: 1