Reputation: 179
I have just started with OOP, so these are my very first babysteps!
I am trying to build a simple booking system where a user can book a time slot that has been created by another user via a calendar. I am at a very early stage of the project, so the database hasn’t been set up yet and I’m currently fiddling around with a day class and a time slot class and trying to figure out how to make them interact.
Here’s my code:
class dayCL {
public $dayInMonth;
public $numBookingSlotsOnDay;
public function __construct($dayInMonth) {
$this->dayInMonth = $dayInMonth;
}
public function getNumBookingSlotsOnDay(){
return "Booking slots: " . $this->numBookingSlotsOnDay;
}
public function numBookingSlotsOnDay(){
$this->numBookingSlotsOnDay = $this->numBookingSlotsOnDay + 1 ;
}
};
class bookingSlotCL {
public $startTime;
public function __construct($startTime) {
$this->startTime = $startTime;
}
public function output(){
return "Start: " . $this->startTime;
}
};
The numBookingSlotsOnDay
function works as intended when called, but is it possible to integrate a call of it in the bookingSlotCL
, so it is called on every instantiation of a bookingSlotCL
?
Example:
$day1 = new dayCL(1);
$bookingSlot1 = new bookingSlotCL(1);
$bookingSlot2 = new bookingSlotCL(1);
Both booking slots are placed on $day1
so $day1->getNumBookingSlotsOnDay
should return “2”.
The calendar is designed so that all days are instantiated as a dayCL
instance, which means that a bookingSlotCL
instance would always have a dayCL
instance to be attached to.
Upvotes: 3
Views: 75
Reputation: 2759
You should add all your bookingSlotCL
instances to an array in your dayCL
instance like this:
$day1 = new dayCL(1);
$day1->addBooking(new bookingSlotCL());
That addBooking
method could look like this:
public function addBooking(dayCL $day) {
$this->days[] = $day;
$day->startTime = $this->dayInMonth
}
This way your are even able to change your getNumBookingSlotsOnDay
method to dynamically determine the number of booking slots:
public function getNumBookingSlotsOnDay() {
return count($this->days);
}
Upvotes: 3
Reputation: 1492
Yes, you can instantiate the class as a property of the class like so then make calls from it:
class bookingSlotCL {
public $startTime;
public $dayCL;
public function __construct($startTime) {
$this->startTime = $startTime;
$this->dayCL = new dayCL();
}
public function output() {
return "Start: " . $this->startTime;
}
};
Call it like this:
$bookingSlotCL = new bookingSlotCL(1);
$bookingSlotCL->dayCL->numBookingSlotsOnDay(1);
Upvotes: 1