나는 PHP와 HTML의 많은 것들에 약간 익숙하므로 저를 참아주세요 :)
그래서 내 PHP 프로젝트의 경우 Calendar
및 CalendarDay
클래스를 사용하여 달력 프로그램을 개발하고 있습니다 . 캘린더를 테이블로 생성했을 때 원래 캘린더가 정상적으로 표시되도록하기 위해 모든 것이 정상적으로 정렬되어 표시되었습니다. 나는 Calendar
클래스 만을 사용 했고 각각의 날짜 / 버튼은 DOM 요소 로 생성되었습니다 . 원래 달력은 여기 이미지 처럼 보였습니다 . 여기서 볼 수있는 모든 셀은 HTML 요소 일 뿐이며 제대로 작동합니다.
그러나 OOP로 전환하여 CalendarDay
클래스를 사용하여 각 달력 날짜를 개별 개체로 생성하려고 하면 더 이상 테이블로 생성되지 않고 대신 이 이미지에 표시된대로 매일 줄 바꿈으로 생성 됩니다. (잘려져 있지만 세로로 한 달에 31 일을 모두 생성합니다. 캘린더와 달리 CSS 스타일도 있습니다.)
객체 출력이 DOM 인 경우 HTML 테이블 내에서 새 PHP 객체를 인스턴스화하여 객체가 여전히 테이블로 정렬되도록 할 수 있습니까?
코드:
class CalendarDay {
public $dayNumber;
public $dayOfWeek;
public $daysArray = [];
public function __construct($dayNumber){
$this->dayNumber = $dayNumber;
$daysArray[] = $dayNumber;
}
public function show(){
$output = '<td>';
$output .= '<div class = "Day"><span>' . $this->dayNumber;
$output .= '</span></div>';
$output .= '</td>';
echo $output;
}
}
임의, 문제와 관련이없는 캘린더 설정 만
class Calendar {
public $month;
public $year;
public $days;
public $week;
public $dayOfWeek;
// Public as may be required for reminders
public $weekdays;
public $daysArray = [];
public function __construct($month, $year, $weekdays = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")){
$this->month = $month;
$this->year = $year;
$this->weekdays = $weekdays;
$this->num_days = cal_days_in_month(CAL_GREGORIAN, $this->month, $this->year);
$this->date_info = getdate(strtotime('first day of', mktime(0,0,0,$this->month, 1 ,$this->year)));
$this->dayOfWeek = $this->date_info['wday']; // get the info including the day of the week that <given_date> falls on
$this->previousDay = getdate(strtotime('first day of', mktime (0,0,0, $this->month-1, 1, $this->year)));
}
public function show(){
// The Calendar is a TABLE with each day as an individual table cell
$output = '<table class = "Calendar">';
// Print the current month and year at the top of the calendar
$output .= '<caption class = "monthName">' . $this->date_info ['month'] . ', ' . $this->year . '</caption>';
// New row to represent the days underneath the month header
$output .= '<tr>';
// Create days of the week header for each day in the array
// For every day in the weekdays array, setting each of them AS a day ($day)
// For each weekday in the calendar table print the day info (i.e. the date)
foreach ( $this->weekdays as $days ){
$output .= '<th class = "header">' . $days . '</th>';
}
// Separate each row of days
$output .= '</tr><tr>';
// IF the first day of a month doesnt fall on a sunday then use COLSPAN to fill the BEGINNING SPACE
if ($this->dayOfWeek > 0){
$output .= '<td colspan="' . $this->dayOfWeek . '"></td>';
}
// The num_days counter, starting from 1
$current_day = 1;
// While loop for building the whole calendar
// While the current day is day number 0 to number of days in the month
// Reset 'day of week' counter and clone each row if end of row
// There are 7 days in a week.
while ($current_day <= $this->num_days) {
if ($this->dayOfWeek == 7){
$this->dayOfWeek = 0; // reset the day numbers for each row of 7 days, so that each row goes from 1, 2... 7 (Sunday to Saturday)
$output .= '</tr><tr>'; // end that row of 7 days and start a new row
}
// Build each day cell (USE FOR LATER IN REMINDERS)
// </td> tag ends a row of days once the day cells per line reaches 7 and creates a new one
여기서 문제는 셀 CalendarDay
내부에 새 개체 를 생성하려고 <td>
하지만 테이블에있는 것처럼 정렬되지 않습니다.
$output .= '<td class = "days">';
$dayObject = new CalendarDay($current_day);
$output .= $dayObject->show();
$output .= '<button class = "calendarDayButton" onclick = "calendarbuttonform.php"><span>' . $current_day . '</span></button></td>';
// Increment counters
// Increase the day
$current_day++;
// Increase the day
$this->dayOfWeek++;
// Store the newly instantiated day in an array
$daysArray[$current_day] = $dayObject;
}
// Once num_days counter stops, if day of week counter is not 7, then fill the remaining space on the row uing COLSPAN
if ($this->dayOfWeek != 7) { // Resets at 7
$remaining_days = 7 - $this->dayOfWeek;
// Amount of remaining days in the week
// span for the remaining days in the week
$output .= '<td colspan="' . $remaining_days .'"></td>'; // span for the remaining days in the week
}
// Close final row once all of the days have been generated, in reference to "current_day++ 11 lines up"
if ($current_day == $this->num_days){
$output .= '</tr>';
$output .= '</table>';
}
echo $output;
}
}
편집 : 다음은 인스턴스화를위한 코드입니다.
<html>
<head>
<link rel = "stylesheet" href = "style.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
</head>
<body>
<?php
$test = new CalendarDay (date("d"));
$test->show();
$test2 = new Calendar (12, 2020);
$test2->show();
?>
</body>
</html>
문제는 다음 두 가지 코드에 있다고 생각합니다.
$output .= '<td class = "days">';
$dayObject = new CalendarDay($current_day);
$output .= $dayObject->show();
$output .= '<button class = "calendarDayButton" onclick = "calendarbuttonform.php"><span>' . $current_day . '</span></button></td>';
public function show(){
$output = '<td>';
$output .= '<div class = "Day"><span>' . $this->dayNumber;
$output .= '</span></div>';
$output .= '</td>';
echo $output;
}
html 출력의이 줄을 참조하십시오.
$output .= $dayObject->show();
이 show()
방법의 줄 :
echo $output;
echo
출력 버퍼에 직접 인쇄합니다 (브라우저로 전송합니다.하지만 당신은 추가하려는 show
의 문자열로 결과를. 가장 간단한 해결책은 변경하는 것 show
에 기능을 return $output
대신 echo $output
.
당신이 구축하고 있기 때문에 $output
문자열을 & 나중에 인쇄,하지만 show()
되어 echo
즉시 보내고, 당신의 HTML은 올바른 순서로 나오는되지 않습니다. 그래서 당신은 아마 많은 <td>
s를 가지고있을 것입니다 <table>
.
EDIT 당신이 경우 정말 당신의 원하는 show
방법을합니다 echo
, 당신이 사용할 수있는 출력 버퍼링 :
$output .= '<td class = "days">';
$dayObject = new CalendarDay($current_day);
ob_start();
$dayObject->show();
$showResult = ob_get_clean();
$output .= $showResult;
$output .= '<button class = "calendarDayButton" onclick =
출력 버퍼링에 대한 정말 훌륭한 사용 사례가 많이 있지만 이것이 그중 하나라고 생각하지 않습니다. 를 반환하는 함수를 추가 한 output
다음 show()
해당 메서드를 호출하고 결과를 에코하도록 할 수도 있습니다. 그런 다음 $output
문자열을 만들 때 다른 함수를 사용 합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다