Reputation: 518
I am new to OOP and therefore would like some help in designing a PHP class and subclass with any interface, if needed and so on. My base class is of type Policy with certain properties and there are specific subclasses of the Policy class with additional properties. My code:
<?php
/* Utility for calculating policy value, getting data from a CSV file
* and then generating output in an XML file.
* First we create the class Policy with all the below properties */
// base class with member properties and method
class Policy{
$policy_number;
$start_date;
$membership;
//Method which calculates the policy value depending on the policy type.
protected function calcPolValue() {
//Creates new xml format
$xml = new SimpleXMLElement('<xml/>');
//Ref: http://php.net/manual/en/function.fgetcsv.php
if (($handle = fopen("MyFile.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$policy_number = $data[0];
$start_date = $data[1];
$membership = $data[2];
//checks whether $property1 string contains letter A
if ((strpos($policy_number, 'A') !== false) and ($start_date < 1990)){
//Policy is PolicyTypeA and its code here
}
elseif ((strpos($policy_number, 'B') !== false) and (strpos($membership, 'Y') !== false)){
//Policy is PolicyTypeB and its code here
}
}
fclose($handle);
}
//add the header and save the xml file in the root folder
Header('Content-type: text/xml');
$xml->saveXML("Policy Values.xml");
}
}
//can I write the subclass like this with the additional properties?
class PolicyTypeA extends Policy {
$management_fee;
}
class PolicyTypeB extends Policy {
$management_fee;
}
?>
How to go on designing the subclass and the method call in OOP? Hope my question is clear.
Upvotes: 0
Views: 169
Reputation: 234
You could keep doing that, and without contextual naming on your parameters it's hard to see what you're really doing here to give much more opinion on the matter. But something about what you posted makes me think that you're shooting a bit wide of the mark of what you want to achieve with what you're doing with that code - I'm not saying it won't work, just that it looks (with the aforementioned lack of context) as though there would be a better way of doing it.
Technically, in simple terms: when you extend a class you inherit everything which that class has in it into the class which is extending it, so you can extend the way you are intending, just know that any dependencies in the parent must be met in the instantiation child as well.
Upvotes: 1