dpmopn8542 2015-01-12 13:28
浏览 69
已采纳

每次都创建新的datetime对象

I have created different vars using date_format from one datetime object $date_obj.

$date_obj = date_create($date);
$year = date_format($date_obj, 'Y');
$month = date_format($date_obj, 'm');
$day = date_format($date_obj, 'd');

However I have read (lost source) that this is bad practice? Instead I should create a new datetime object each time because the original object isn't referenced, but directly manipulated.

$date_obj_1 = date_create($date);
$year = date_format($date_obj_1, 'Y');

$date_obj_2 = date_create($date);
$month = date_format($date_obj_2, 'm');

$date_obj_3 = date_create($date);
$day = date_format($date_obj_3, 'd');

Is this true?

  • 写回答

2条回答 默认 最新

  • dpt62283 2015-01-12 13:36
    关注

    The DateTime object is an object, and therefore is passed by reference.

    In your example above this won't matter, because you only format a date, you do not manipulate it. However, if you use a DateTime object as an argument in a function and inside this function you manipulate the object, your changes will be visible outside of that function:

    function addDays($date,$days){
            $date->add(new DateInterval($days.' days'));
    }
    
    $date_obj_1 = date_create($date);
    
    $formatedDate1 = date_format($date_obj_1, 'Y-m-d');
    addDays($date_obj_1,10);
    $formatedDate2 = date_format($date_obj_1, 'Y-m-d');
    

    In the above example $formatedDate1 is different from $formatedDate1 because $date_obj_1 was passed by reference


    EDIT: for a detailed explanation on my above snipped look at the comments section. @Xatoo explained it pretty good.

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

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计