если оператор заставляет функцию не работать

У меня есть следующее утверждение в моем классе и в функции. Теперь, когда обернуть это если заявление

$this->setDayData(15, "test content = " .$list_day . "<br>");

не работает, но если я удаляю оператор if и просто сохраняю его там, он работает нормально. Последние несколько дней я ломал голову над тем, почему это происходит и не работает.

for($list_day = 1; $list_day <= $days_in_month; $list_day++){
if($list_day == 15){
$this->setDayData(15, "test content = " .$list_day . "<br>");
}
}

и я знаю, что эта проверка работает if($list_day == 15) потому что, если я повторяю что-то в с там, это работает. Я не могу понять, почему это, если заявление вызвало бы $this->setDayData(15, "test content = " .$list_day . "<br>"); не работать.

Может кто-нибудь, пожалуйста, помогите мне с этим?

<?php
class Calendar{
/**
* holds the list of months
*
* @var array
* @access private
*/
private $_months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

/**
* holds the list of days
*
* @var array
* @access private
*/
private $_days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

/**
* holds all of the css class definitions
*
* @var array
* @access private
*/
private $_class_defintions = array();

/**
* holds the month
*
* @var integer
* @access private
*/
private $_month;

/**
* holds the year
*
* @var integer
* @access private
*/
private $_year;

/**
* holds data that will be filled in each day
* the indexes are zero-keyed
*
* @var array
* @access private
*/
private $_day_data = array();

/**
* class constructor
*
* @param string|integer $month -- defines the month to be used in the calendar
* @param integer $year -- defines the year
* @param array $day_data -- zero-key index to define the data that will be displayed with each day
* @access public
* @return void
*/
public function __construct($month = false, $year = false, array $day_data = array()){
include "config/config.php";
$this->setMonth($month)
->setYear($year)
->setMultipleDayData($day_data)
->setDefaultClassDefinitions();

try {
// Generate a database connection, using the PDO connector
// @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
// Also important: We include the charset, as leaving it out seems to be a security issue:
// @see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Connecting_to_MySQL says:
// "Adding the charset to the DSN is very important for security reasons,
// most examples you'll see around leave it out. MAKE SURE TO INCLUDE THE CHARSET!"$this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
} catch (PDOException $e) {
$this->errors[] = MESSAGE_DATABASE_ERROR . $e->getMessage();
}
}/**
* Checks if database connection is opened. If not, then this method tries to open it.
* @return bool Success status of the database connecting process
*/
private function databaseConnection()
{
include "config/config.php";
// if connection already exists
if ($this->db_connection != null) {
return true;
} else {
try {
// Generate a database connection, using the PDO connector
// @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
// Also important: We include the charset, as leaving it out seems to be a security issue:
// @see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Connecting_to_MySQL says:
// "Adding the charset to the DSN is very important for security reasons,
// most examples you'll see around leave it out. MAKE SURE TO INCLUDE THE CHARSET!"$this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
return true;
} catch (PDOException $e) {
$this->errors[] = MESSAGE_DATABASE_ERROR . $e->getMessage();
}
}
// default return
return false;
}

/**
* Search into database for the days that have tasks and month is passed as a parameter
* @return PDO query
* @return false if nothing is found for that month
*/
private function getTaskDays($month)
{
// if database connection opened
//if ($this->databaseConnection()) {
// database query, getting all the info of the selected user
$query_tasks = $this->db_connection->prepare('SELECT DAYOFMONTH(due_date) AS Day FROM tbl_tasks WHERE status = "active" AND MONTH(due_date) = :month');
$query_tasks->bindValue(':month', $month, PDO::PARAM_STR);
$query_tasks->execute();
// get result row (as an object)
return $query_tasks->fetchAll(PDO::FETCH_COLUMN, 0);
//} else {
return false;
//}
}

/**
* Converts array that is generated by PDO and converts into csv list
* @return csv list
*/
private function getListDays($month){
$qry  = $this->getTaskDays($month);
$list = implode(",", $qry);
return $list;
}/**
* Checks to see if number(which should be current day is in list of tasks)
* @return true
* @return false if nothing is found
*/
private function checkDay($day, $list){
$dates = explode(',', $list);
return in_array($day, $dates);
}/**
* this method sets the css to be used in the calendar creation see {@link: $_class_definitions} for allowed keys
*
* @param array $settings
* @access public
* @return System_Utility_Calendar
*/
public function setCssDefinitions(array $settings = array()){
$this->_class_defintions = array_merge($this->_class_defintions, $settings);

return $this;
}

/**
* this method sets the month value
* it will convert a sting-based value to an integer one
* if no month is passed in, it will use the current month
*
* @param string|integer $month -- defines the month to be used in the calendar
* @access public
* @return System_Utility_Calendar
*/
public function setMonth($month = false){
if(!(bool) $month){
$month = date('n', time());
}elseif(!is_int($month)){
foreach($this->_months as $key => $name){
if(preg_match('/^'. $month .'/i', $name)){
$month = $key + 1;

break;
}
}
}

$this->_month = $month;

return $this;
}

/**
* sets the year
* if no year is passed it, it will use the current year
*
* @param integer $year
* @access public
* @return System_Utility_Calendar
*/
public function setYear($year){
if(!isset($year)){
$year = date('Y', time());
}

$this->_year = $year;

return $this;
}

/**
* method used to assign how the days of the week will be displayed
*
* @param array $days
* @access public
* @return System_Utility_Calendar
*/
public function setDaysOfWeek(array $days = array()){
$this->_days = $days;

return $this;
}

/**
* sets the data for each day of the month
* uses a zero key index
*
* @param array $data -- the key is the day (actual day minus one) the value is the data to be passed in that day
* @param boolean $append -- this will say to overwrite the day or not with the data. Defaults to true
* @access public
* @return System_Utility_Calendar
*/
public function setMultipleDayData(array $data = array(), $append = true){
if(count($data)){
foreach($data as $day => $content){
$this->setDayData($day, $content, $append);
}
}

return $this;
}

/**
* sets the data for a given day
*
* @param integer $day -- the zero key of the day to be modified
* @param mixed $content -- the content for that day
* @param boolean $append -- this will say to overwrite the day or not with the data. Defaults to true
* @access public
* @return return type
*/
public function setDayData($day, $content, $append = true){
$current_content       = isset($this->_day_data[$day]) ? $this->_day_data[$day] : '';
$this->_day_data[$day] = $append ? $current_content . $content : $content;

return $this;
}/**
* this creates the calendar
*
* @access public
* @return string
*/
public function build(){
$running_day       = date('w', mktime(0, 0, 0, $this->_month, 1, $this->_year));
$days_in_month     = date('t', mktime(0, 0, 0, $this->_month, 1, $this->_year));
$days_in_this_week = 1;
$day_counter       = 0;
$rows              = array();
$row_count         = 6;
$day_head          = $this->dayHead();
$month_head        = $this->monthHead();
$cells             = '';
$listDays          = $this->getListDays($this->_month);/**
* create the leading empty cells
*/
for($x = 0; $x < $running_day; $x++){
$cells .= $this->day(false);

$days_in_this_week++;
}

/**
* creates the rest of the days for the week
* if it is the last day of the week, wrap the cells in a row
*/
for($list_day = 1; $list_day <= $days_in_month; $list_day++){
$cells .= $this->day($list_day);if($list_day == 15){

echo "the day is 15 " . $list_day . "<br>";
$this->setDayData(15, "test content = " .$list_day . "<br>");

}if($running_day == 6){
$rows[]            = $this->row($cells, $this->_class_defintions['row']);
$cells             = '';
$running_day       = -1;
$days_in_this_week = 0;

$row_count--;
}

$days_in_this_week++;
$running_day++;
$day_counter++;
}/**
* build the trailing empty days
*/
if($days_in_this_week < 8){
for($x = 1; $x <= (8 - $days_in_this_week); $x++){
$cells .= $this->day(false);
}

$row_count--;
}

$rows[] = $this->row($cells, $this->_class_defintions['row']);

/**
* if there are still rows left, create an empty row
*/
if($row_count > 0){
$empty = '';

for($x = 1; $x <= 7; $x++){
$empty .= $this->day(false);
}

$rows[] = $this->row($empty, $this->_class_defintions['row']);
}

return $this->table($month_head . $day_head . implode('', $rows));
}

/**
* resets the class so that the same instance can be used to create another month
*
* @access public
* @return System_Utility_Calendar
*/
public function reset(){
$this->_month    = false;
$this->_year     = false;
$this->_day_data = array();

return $this->setDefaultClassDefinitions();
}

/**
* method used to create the outlining table
*
* @param string $content -- the rows and cells
* @access private
* @return string
*/
private function table($content){
return '
<table cellpadding="0" cellspacing="0" class="'. $this->_class_defintions['calendar'] .'">
<tbody>
'. $content .'
</tbody>
</table>
';
}

/**
* method used to display the month heading
*
* @access private
* @return string
*/
private function monthHead(){
return '
<tr class="'. $this->_class_defintions['month_head'] .'">
<td class="'. $this->_class_defintions['heading'] .'" colspan="7">'. $this->_months[($this->_month - 1)] .'</td>
</tr>
';
}

/**
* method used to create the day heading
*
* @access private
* @return string
*/
private function dayHead(){
return '
<tr class="'. $this->_class_defintions['row'] .'">
<td class="'. $this->_class_defintions['heading'] .'">'. implode('</td><td class="'. $this->_class_defintions['heading'] .'">', $this->_days). '</td>
</tr>
';
}

/**
* this method will build out a day in the calendar
* if false is passed in for the day, an empty day cell will be returned
*
* @param integer|booean $day -- the current day of the month that is being built
* @access private
* @return string
*/
private function day($day){
if((bool) $day){
$class   = $this->_class_defintions['working_day'];
$content = isset($this->_day_data[($day)]) ? $this->_day_data[($day)] : '';
$day_num = '<div class="'. $this->_class_defintions['day_number'] .'">'. $day .'</div>';

/**
* if there is content, set the class to whatever is content_day
*/
if($content !== ''){
$class = $this->_class_defintions['content_day'];
}
}else{
$class   = $this->_class_defintions['blank_day'];
$content = '';
$day_num = '';
}

return '
<td class="'. $class. '">
<div class="calendar_day_container">
'. $day_num . $content .'
</div>
</td>
';
}

/**
* method creates a week row
*
* @param string $content -- the cells that will fill the row
* @param string $class -- the class to be used on the row
* @access private
* @return string
*/
private function row($content, $class = ''){
return '
<tr class="'. $class .'">
'. $content .'
</tr>
';
}

/**
* method used to define the default class names
*
* @access private
* @return System_Utility_Calendar
*/
private function setDefaultClassDefinitions(){
return $this->setCssDefinitions(array(
'blank_day'   => 'calendar-day-np',
'working_day' => 'calendar-day',
'content_day' => 'calendar-day-content',
'day_number'  => 'day-number',
'month_head'  => 'month-head',
'row'         => 'calendar-row',
'heading'     => 'calendar-day-head',
'calendar'    => 'calendar'
));
}
}
?>

1

Решение

Отредактировано — с решением

Как я уже сказал, проблема была не в функции, а в логике вашего класса.

В build() метод у вас есть такая часть кода:

$cells .= $this->day($list_day);if($list_day == 15){

echo "the day is 15 " . $list_day . "<br>";
$this->setDayData(15, "test content = " .$list_day . "<br>");

}

Проблема в том, что вы должны изменить порядок этих действий:

if($list_day == 15){

echo "the day is 15 " . $list_day . "<br>";
$this->setDayData(15, "test content = " .$list_day . "<br>");

}

$cells .= $this->day($list_day);

Теперь даже если вы используете if все работает нормально, как я уже сказал, это не имеет ничего общего с setDayData функция, потому что эта функция ничего не отображает.

Отредактированный ответ после добавления полного кода класса

В вашем коде нет ошибок. функция setDayData выполняется как надо. Если вы идете к своей функции build и после окончания цикла:

for($list_day = 1; $list_day <= $days_in_month; $list_day++){
// rest of code
}

вы добавляете:

var_dump ($ это -> _ day_data);

вы получите результат:

array(1) { [15]=> string(21) "test content = 15
" }

так как вы видите, что функция выполняется и присваиваете содержимое переменной, как и должно быть.

Предыдущий ответ

В этом коде нет ошибки.

Когда я запускаю следующий код, основанный на том, что вы вставили в свой вопрос:

<?phpclass Test
{

public function foo()
{
$days_in_month = 100;
for ($list_day = 1; $list_day <= $days_in_month; $list_day++) {
if ($list_day == 15) {
$this->setDayData(15, "test content = " . $list_day . "<br>");
}
}

echo $this->_day_data[15];
}public function setDayData($day, $content, $append = true)
{

$current_content = isset($this->_day_data[$day])
? $this->_day_data[$day] : '';
$this->_day_data[$day] = $append ? $current_content . $content
: $content;

return $this;
}

}$x = new Test();

$x->foo();

вывод:

test content = 15<br>

как и ожидалось.

Вы должны определенно оценить $days_in_month значение, потому что если оно меньше 15, функция, конечно, не будет запущена. Если его значение больше 15, вы должны искать ошибку в другой части вашего кода.

1

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]