简体   繁体   中英

Method not functioning as expected when extending PHP class

I am using the PHP Carbon library in my Laravel 4 application. I've successfully extended the \\Carbon\\Carbon class into my own \\Extensions\\Carbon class. My new class file contains the following:

<?php namespace Extensions;

class Carbon extends \Carbon\Carbon {


        public function __construct()
        {
                parent::__construct();
        }

}

This seems to be working correctly since I am now able to create objects using this class. However, when I try to use the copy() method, I see something strange:

[1] > $dt = new \Extensions\Carbon;
// object(Extensions\Carbon)(
//   'date' => '2015-06-12 20:14:45',
//   'timezone_type' => 3,
//   'timezone' => 'UTC'
// )
[2] > $dt->addDays(2);
// object(Extensions\Carbon)(
//   'date' => '2015-06-14 20:14:45',
//   'timezone_type' => 3,
//   'timezone' => 'UTC'
// )
[3] > $dt->copy();
// object(Extensions\Carbon)(
//   'date' => '2015-06-12 20:14:54',
//   'timezone_type' => 3,
//   'timezone' => 'UTC'
// )

Why does the copy method output the value of date before I added 2 days? If I do this same thing using the original Carbon class, it works correctly:

[1] > $dt = new Carbon\Carbon;
// object(Carbon\Carbon)(
//   'date' => '2015-06-12 20:22:51',
//   'timezone_type' => 3,
//   'timezone' => 'UTC'
// )
[2] > $dt->addDays(2);
// object(Carbon\Carbon)(
//   'date' => '2015-06-14 20:22:51',
//   'timezone_type' => 3,
//   'timezone' => 'UTC'
// )
[3] > $dt->copy();
// object(Carbon\Carbon)(
//   'date' => '2015-06-14 20:22:51',
//   'timezone_type' => 3,
//   'timezone' => 'UTC'
// )

Any idea what could cause this behavior?

Looks like I wasn't using the proper constructor. This works as expected:

public function __construct($time = null, $tz = null)
{
    parent::__construct($time, $tz);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM