PHP - Private class variables giving error: undefined variable

后端 未结 4 858
礼貌的吻别
礼貌的吻别 2021-01-04 04:28

I am getting the error \"Undefined variable: interval in C:\\wamp\\www\\DGC\\classes\\DateFilter.php\"

Here is my code for the DateFilter class:

clas         


        
相关标签:
4条回答
  • 2021-01-04 04:56
    function test()
    {
        echo $this->interval->format("%d days old </br>");
    }
    
    0 讨论(0)
  • 2021-01-04 04:57

    You have to use $this->interval to access the member variable interval in PHP. See PHP: The Basics

    class DateFilter extends Filter
    {
        private $interval;    // this is correct.
    
        public function DateFilter($daysOld)
        {
            $this->interval = new DateInterval('P'.$daysOld.'D');   // fix this
        }
    
        function test()
        {
            echo $this->interval->format("%d days old </br>");     // and fix this
        }
    }
    
    0 讨论(0)
  • 2021-01-04 05:03

    $interval is local to the function. $this->interval references your private property.

    class DateFilter extends Filter
    {
        //@param daysOld: how many days can be passed to be included in filter
        //Ex. If daysOld = 7, everything that is less than a week old is included
        private $interval;
    
        public function DateFilter($daysOld)
        {
            echo 'days old' . $daysOld .'</ br>';
            $this->interval = new DateInterval('P'.$daysOld.'D');
        }
    
    
        function test()
        {
            echo $this->interval->format("%d days old </br>");
            //echo 'bla';
        }
    
    }
    
    0 讨论(0)
  • 2021-01-04 05:15

    trying

    public var $interval;
    

    and

    echo $this->interval;
    
    0 讨论(0)
提交回复
热议问题