PHP - Private class variables giving error: undefined variable

家住魔仙堡 提交于 2019-12-01 14:07:24

问题


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

Here is my code for the DateFilter class:

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>';
        $interval = new DateInterval('P'.$daysOld.'D');
    }


    function test()
    {
        echo $interval->format("%d days old </br>");
        //echo 'bla';
    }

}

When I create a new instance of the DateFilter class and call test() it give me the error. I realize it means the variable hasn't been initialized, but I know that the constructor is being called because I put an echo statement in there and it was output.

I have also tried: $this::$interval->format(...); self::$interval->format(...); but it didn't work.

I know this is probably an easy fix, sorry for the noob question. Can't believe this stumped me.


回答1:


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
    }
}



回答2:


$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';
    }

}



回答3:


function test()
{
    echo $this->interval->format("%d days old </br>");
}



回答4:


trying

public var $interval;

and

echo $this->interval;


来源:https://stackoverflow.com/questions/7747452/php-private-class-variables-giving-error-undefined-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!