drbxr86044 2011-03-21 12:50
浏览 47
已采纳

访问除返回值以外的函数中的变量

I need an help to understand this problem I am facing...and apologies if it seems silly.

I wrote a function that makes some calculations according to two differents dates (arrival and departure). It all works fine, the returned values is given and it is correct.

Nevertheless while this calculation is made there is variable created ($days) which I would like to use (echo) outside the function. I have tried to make it global but I get an error...guessing that I am on the wrong path!

So my question is how do you get a value inside a function other than the returned value? if it is at all possible of course.

code below:

function costs($date1, $date2, $price) {

$arr= explode("/", $date1);
$timestamp1 = mktime(0,0,0,$arr[1],$arr[0],$arr[2]);

$arr2= explode("/", $date2);
$timestamp2 = mktime(0,0,0,$arr2[1],$arr2[0],$arr2[2]);

$timestamp = $timestamp2 - $timestamp1;
$days = $timestamp/86400;

$cost = $days * $price;

return $cost;

}     

Appreciated any little help to understand this. Francesco

  • 写回答

6条回答 默认 最新

  • doulei6330 2011-03-21 13:05
    关注

    These should really be two separate functions, with the one using the other.

    function costs($date1, $date2, $price) {
        $cost = days($date1, $date2) * $price;
        return $cost; 
    }
    
    function days($date1, $date2) {
        $arr= explode("/", $date1); 
        $timestamp1 = mktime(0,0,0,$arr[1],$arr[0],$arr[2]); 
    
        $arr2= explode("/", $date2); 
        $timestamp2 = mktime(0,0,0,$arr2[1],$arr2[0],$arr2[2]); 
    
        $timestamp = $timestamp2 - $timestamp1; 
    
        return $timestamp/86400;
    }
    

    EDIT: Then you can call either function depending on what you want without duplicating code.

    It doesn't look like you're using objects, so I won't give you the OO spiel, but you can definitely split these up into separate functions so you're not doing wierd stuff with globals and muddying up your namespaces.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?