duanheye7423 2015-09-24 14:08
浏览 104
已采纳

一个类中的实例是否可以在另一个类的实例中更改变量?

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.

  • 写回答

2条回答 默认 最新

  • dqnrk44682 2015-09-24 14:18
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度