Re: Question regarding OO
| From: | Ted Wood | Date: | Fri, 11 Jul 2008 16:16:58 +0000 |
| Subject: | Re: Question regarding OO | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-276658@lists.php.net to get a copy of this message | ||
Object-oriented programming, with it's "class" and "object" approach, is meant to model real life more closely than functional programming.
In, a "parking space" is physically inside a "parking lot", but a parking space is not a subclass of a parking lot. It's not a variation or mini parking lot. It's an entirely different entity. A parking lot consists of parking spaces, but a parking space is its own thing.
In other words, don't extend ParkingSpace from ParkingLot. They should be separate classes entirely.
As for the recursion... no, that won't be a problem. Each ParkingSpace you're instantiating is a separate instance, and won't be related to the parent ParkingLot in anyway way internally.
<?php
class ParkingSpace {
var $size;
var $num_spaces;
var $spaces = array();
}
class ParkingSpace {
var $ps_ID;
var $occupied_by;
var $st_time;
}
?>
In the above class definition, simply populate the $spaces array with instances of the ParkingSpace class.
~Ted
On 11-Jul-08, at 9:03 AM, Yeti wrote:
<?php /* I have a question here regarding object orientation in PHP and any other language. Let's start with some hypothetical code: */ // <--- 1st CLASS class ParkingLot { var size; // size in sq feet var max_number_of_cars; // how many cars there is space for function __construct($size, $max_cars) { $this->size = $size; $this->max_number_of_cars = $max_cars; } }; cpark = new ParkingLot(50000, 17); // <--- 2nd CLASS class ParkingSpace extends ParkingLot { var ps_ID; // ID of the parking space ( 1 .. max_number_of_cars ) var occupied_by; // ID of the car on the parking space var st_time; // Unix time stamp set when the car parks function __construct($car, $id) { $this->st_time = time(); $this->occupied_by = $car; $this->ps_ID = $id; } }; /* OK, so i got a parking lot class and its subclass parking space. Now the question: I want a list of occupied parking spaces, where do I put that? One might put it into the ParkingLot Class, but wouldn't that be a recursion (a child instance in the parent class)? */ $occ_parking_spaces = array(); $occ_parking_spaces[] =& new ParkingSpace('Joes Car', 8); $occ_parking_spaces[] =& new ParkingSpace('My Prshe', 17); $occ_parking_spaces[] =& new ParkingSpace('Toms Caddy', 4); /* After a while a method to print all occupied spaces is necessary. Correct me if I'm wrong, but I usually add it to the ParkingLot class. class ParkingLot { // previous code ... var $occ_parking_spaces = array(); function print_occ_spaces() { var_dump($this->occ_parking_spaces) } }; What bothers me here is that I'm actually having a list of child classes in the parent class, is there a better/correct way to do this? I hope I made myself clear. Greetz, Yeti */ ?>