if语句导致函数不运行

时间:2014-09-17 19:23:53

标签: php function php-5.4

我在课堂上和函数中都有以下语句。现在将它包装在if语句中

$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),因为如果我在其中回应某些内容,那么它就可以了。我无法理解为什么if语句会导致$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 个答案:

答案 0 :(得分: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($这 - &GT; _day_data);

你会得到结果:

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

因此,当您看到正在执行函数并将内容分配给变量时,应该这样做。

上一个回答

此代码中没有错误。

根据您提出的问题运行以下代码时:

<?php


class 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,您应该在代码的其他部分查找错误。