PHP - 私有(private)类变量给出错误 : undefined variable

标签 php class variables private

我收到错误“ undefined variable :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(...); self::$interval->format(...); 但它没有用。

我知道这可能是一个简单的解决方法,对于菜鸟问题​​深表歉意。不敢相信这难倒了我。

最佳答案

在PHP中你必须使用$this->interval来访问成员变量interval。参见 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 - 私有(private)类变量给出错误 : undefined variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7747452/

相关文章:

python - 比较python类中的变量

ios - 停止Titanium Appcelerator中其他选项卡的声音

PHP 文件无法识别从 ajax 文件发送的数据

javascript - 使用 javascript/jquery 加载文件

php - 从 CSV 文件插入链接

php - 我如何查看多个文件上传PHP中数组是否为空

php - Python 脚本在 PHP 中运行时会跳过 os 和 glob 模块

python - 向内置函数添加方法

java - 对象不是抽象的,不会覆盖抽象方法

php - 图标未加载