我收到错误“ 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/