我正在尝试编写一个PHP程序来计算某个日期的年,月和日数,并在我尝试获得结果时收到错误:
致命错误:在写上下文中不能使用函数返回值
此行显示错误:
$values($years, $months, $days) = $c->difference($diff);
完整的代码是:
<?php
class Calculator {
public $diff = NULL;
public function calculate ($birthday) {
$date = date('m/d/y', time());
$diff = abs(strtotime($date) - strtotime($birthday));
return $diff;
}
public function difference ($diff) {
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
return array($years, $months, $days);
}
}
$c = new Calculator;
$diff = $c->calculate("11/13/1995");
$values($years, $months, $days) = $c->difference($diff);
echo $values[0] . " years, " . $values[1] . " months, " . $values[2] . " days.";
?>
为什么我收到此错误?
答案 0 :(得分:2)
您需要使用list()
:
$values($years, $months, $days) = $c->difference($diff);
应该是:
list($years, $months, $days) = $c->difference($diff);
或者使用当前的回声,只需分配给数组$values
:
$values = $c->difference($diff);
看起来你正在尝试两者的混合。
答案 1 :(得分:1)
简单地
$values = $c->difference($diff);
值将保存返回的数组。