在heredoc中调用php函数

时间:2012-01-11 14:36:49

标签: php class function heredoc

我正试图从一个heredoc中调用一个函数,我在manual(例如#2)中读到它是可能的。但是,我收到以下错误:Notice: Undefined property: TIME::$since on line 13

1   <?php class TIME {
2       var $month;
3       var $year;
4       public function since($y) {
5           $this->$month = (date("F"));
6           $this->$year = (date("Y")-$y);
7           return "(since $month of $year)";
8           // return "(since date('F') of {date('Y')-$y})";
9       }
10  }
11  $time = new TIME;
12  echo <<<EOF
13      {$time->since{1}};
14  EOF; ?>

我需要做的是将1作为整数传递给函数since()并返回类似(since January of 2011)的字符串。

3 个答案:

答案 0 :(得分:4)

它是$time->since(1)。使用since{1}被解释为&#34;给我存储在$ time对象属性中的字符串的第二个字符,称为&#39;&#39;&#34;&#34;。

e.g:

$x = 'hello';
echo $x{0}; // outputs 'h'
echo $x{2}; // outputs 'l'

答案 1 :(得分:1)

一切都按预期工作,但您没有属性$since,而是方法since()。只需将其称为方法

即可
$time->since(1);

此处{1}是数组访问的替代语法。

答案 2 :(得分:1)

您的代码中存在很多错误。在您的情况下,$this->$month$this->$year必须为$this->month$this->year,我认为return "(since $month of $year)";必须为return "(since {$this->month} of {$this->year})";{$time->since{1}};可能是{$time->since(1)};,最后是EOF; ?> - 关闭heredoc时,结束PHP标记必须在换行符上:

EOF;
?>

P.S。为什么使用旧的PHP4风格的属性声明?