Req #49188 [Opn]: DateTime::__construct should allow a DateTime-object to be passed as argument

From: Date: Mon, 20 Jun 2016 16:12:51 +0000
Subject: Req #49188 [Opn]: DateTime::__construct should allow a DateTime-object to be passed as argument
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-201758@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=49188&edit=1

 ID:                 49188
 Updated by:         cmb@php.net
 Reported by:        niklas at narhinen dot net
 Summary:            DateTime::__construct should allow a DateTime-object
                     to be passed as argument
 Status:             Open
 Type:               Feature/Change Request
 Package:            Date/time related
 PHP Version:        5.2.10
 Block user comment: N
 Private report:     N

 New Comment:

> DateTime::__construct should allow a DateTime object to be
> passed as parameter to emulate good object desing (Copy
> constructor).

PHP has clone for this purpose. In my opinion, that's pretty
fine.


Previous Comments:
------------------------------------------------------------------------
[2012-12-04 20:16:31] will dot sskates at ntlworld dot com

You can pass the time string instead. What is the use case for this?

------------------------------------------------------------------------
[2009-08-07 08:18:54] niklas at narhinen dot net

Description:
------------
DateTime::__construct should allow a DateTime object to be passed as parameter to emulate good
object desing (Copy constructor).

This wouldn't break anything.

Reproduce code:
---------------
<?php
date_default_timezone_set('Europe/Helsinki');

class MyClass
{
	private $myDateTime;
	public function setTime($datetime = null) { $this->myDateTime = new DateTime($datetime); }
	public function getTime($format = "Y-m-d") { return
$this->myDateTime->format($format); }
}

$class = new MyClass();
$class->setTime("7.8.2009");
var_dump($class->getTime());
$class->setTime(null);
var_dump($class->getTime());
$dt = new DateTime('15.5.2005');
$class->setTime($dt);
var_dump($class->getTime());
?>

Expected result:
----------------
string(10) "2009-08-07"
string(10) "2009-08-07"
string(10) "2005-05-15"

Actual result:
--------------
string(10) "2009-08-07"
string(10) "2009-08-07"
PHP Fatal error:  Uncaught exception 'Exception' with message
'DateTime::__construct() expects parameter 1 to be string, object gi
ven' in D:\temp\php\datetime.php:7
Stack trace:
#0 D:\temp\php\datetime.php(7): DateTime->__construct(Object(DateTime))
#1 D:\temp\php\datetime.php(17): MyClass->setTime(Object(DateTime))
#2 {main}
  thrown in D:\temp\php\datetime.php on line 7


------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=49188&edit=1


Thread (4 messages)

« previous php.bugs (#201758) next »