PHP - 给出错误的私有类变量:未定义的变量

2022-08-30 20:46:38

我收到错误“未定义变量:C中的间隔:\wamp\www\DGC\classes\DateFilter.php”

以下是我对 DateFilter 类的代码:

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

}

当我创建 DateFilter 类的新实例并调用 test() 时,它会给我错误。我意识到这意味着变量尚未初始化,但我知道构造函数正在被调用,因为我在那里放了一个echo语句并且它是输出的。

我也尝试过: $this::$interval->format(...);自我::$interval->格式(...);但它不起作用。

我知道这可能是一个简单的解决方案,对不起菜鸟问题。不敢相信这让我感到困惑。


答案 1

您必须使用 来访问 PHP 中的成员变量。参见 PHP: The Basics$this->intervalinterval

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是函数的本地。 引用您的私有财产。$this->interval

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

}

推荐