PHP-私有类变量给出错误:未定义的变量 [英] PHP - Private class variables giving error: undefined variable

查看:118
本文介绍了PHP-私有类变量给出错误:未定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这里是我的DateFilter类的代码:

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

}

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

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也尝试过:
$ this :: $ interval-> format(...);
self :: $ interval-> format(...);
,但是它没有用。

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.

推荐答案

您必须使用 $ this-> interval 访问PHP中的成员变量 interval 。参见 PHP:基础知识

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

这篇关于PHP-私有类变量给出错误:未定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆