【问题标题】:php call function within heredocheredoc中的php调用函数
【发布时间】:2012-02-07 21:56:39
【问题描述】:

我正在尝试从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) 的字符串。

【问题讨论】:

  • since{1} 应该是 since(1) - 因为它是一个函数调用
  • 您是否尝试过重命名您的班级,比如说 TimeSince ?
  • 如果你尝试{$time-&gt;since(1)} 而不是{$time-&gt;since{1}}?

标签: php class function heredoc


【解决方案1】:

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

例如:

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

【讨论】:

    【解决方案2】:

    一切都按预期工作,但您没有属性$since,而是方法since()。像方法一样调用它

    $time->since(1);
    

    这里的{1} 是数组访问的替代语法。

    【讨论】:

      【解决方案3】:

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

      EOF;
      ?>
      

      附:为什么要使用旧的 PHP4 风格的属性声明?

      【讨论】:

      • 哦,哇,这解释了很多^^,谢谢!顺便说一句,“PHP4 风格的属性声明”是什么意思?
      • @jacob timur 指的是这个:var $month; 检查这个:PHP5 Variables Basics docs
      • @ThinkingMonkey,我通常不会这样做,但由于遇到问题,我尝试按照页面上的示例进行操作。
      • @jacob 所以,我认为,您现在不需要使用 var 关键字来代替 public 或其他东西 :)
      猜你喜欢
      • 2019-04-07
      • 2021-07-21
      • 2016-08-24
      • 2014-09-27
      • 2013-02-24
      • 2015-12-29
      • 2013-06-15
      • 1970-01-01
      相关资源
      最近更新 更多