PHP - 私有类变量给出错误:未定义的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7747452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - Private class variables giving error: undefined variable
提问by CHawk
I am getting the error "Undefined variable: interval in C:\wamp\www\DGC\classes\DateFilter.php"
我收到错误“未定义变量:C:\wamp\www\DGC\classes\DateFilter.php 中的间隔”
Here is my code for the DateFilter class:
这是我的 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';
}
}
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.
当我创建 DateFilter 类的新实例并调用 test() 时,它给了我错误。我意识到这意味着变量尚未初始化,但我知道正在调用构造函数,因为我在其中放置了一个 echo 语句并且它是输出。
I have also tried: $this::$interval->format(...); self::$interval->format(...); but it didn't work.
我也试过: $this::$interval->format(...); self::$interval->format(...); 但它没有用。
I know this is probably an easy fix, sorry for the noob question. Can't believe this stumped me.
我知道这可能是一个简单的解决方法,对于菜鸟问题很抱歉。不敢相信这让我很难过。
回答by Jonathon Reinhart
You have to use $this->interval
to access the member variable interval
in PHP. See PHP: The Basics
您必须使用$this->interval
来访问interval
PHP 中的成员变量。请参阅PHP:基础知识
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
}
}
回答by Herbert
$interval
is local to the function. $this->interval
references your private property.
$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';
}
}
回答by CheeseSucker
function test()
{
echo $this->interval->format("%d days old </br>");
}
回答by Jan Wiemers
trying
试
public var $interval;
and
和
echo $this->interval;