在公共类中实现变量

时间:2015-02-23 11:58:09

标签: php oop

class booking_diary {

    $start_timeS="09:30";
    $bookingS_start_time= "19:00";
    $bookingS_frequency=30;`enter code here`



    public $booking_start_time   =$start_timeS ;    // The time of the first slot in  
    public $booking_end_time =$bookingS_start_time; // The time of the last slot in  
    public $booking_frequency= $bookingS_frequency;  // The slot frequency per hour,    

我可以这样做吗?

1 个答案:

答案 0 :(得分:0)

没有。您不能在类块中放置自定义代码(此处为您的变量)。

如果您不想初始化类字段,可以使用类构造函数

<?php
class booking_diary {

    public $booking_start_time;
    public $booking_end_time;
    public $booking_frequency;

    public function __construct() {
        $start_timeS="09:30";
        $bookingS_start_time= "19:00";
        $bookingS_frequency=30;
        //`enter code here`

        $this->booking_start_time = $start_timeS;
        $this->booking_end_time = $bookingS_start_time;
        $this->booking_frequency = $bookingS_frequency;
    }
}

如果你想从外面用变量提供课程,也许这样的东西可以满足你的需求:

<?php
class booking_diary {

    public $booking_start_time;
    public $booking_end_time;
    public $booking_frequency;

    public function __construct($booking_start_time, $booking_end_time, $booking_frequency) {
        $this->booking_start_time = $booking_start_time;
        $this->booking_end_time = $booking_end_time;
        $this->booking_frequency = $booking_frequency;
    }
}

// Somewhere in your code:

$start_timeS="09:30";
$bookingS_start_time= "19:00";
$bookingS_frequency=30;
//`enter code here`

$instance = new booking_diary($start_timeS, $bookingS_start_time, $bookingS_frequency);