Asked  7 Months ago    Answers:  5   Viewed   40 times

Using the DateTime class, if I try to run the following code:

$mydate = new DateTime();
echo $mydate->date;

I'll get back this error message

Notice: Undefined property: DateTime::$date...

Which doesn't make sense because when running var_dump() on the variable $mydate, it clearly shows that this property exists and is publicly accessible:

var_dump($mydate);

object(DateTime)[1]
  public 'date' => string '2012-12-29 17:19:25' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

Is this a bug within PHP or am I doing something wrong? I'm using PHP 5.4.3.

 Answers

91

This is a known issue.

Date being available is actually a side-effect of support for var_dump() here – derick@php.net

For some reason, you're not supposed to be able to access the property but var_dump shows it anyways. If you really want to get the date in that format, use the DateTime::format() function.

echo $mydate->format('Y-m-d H:i:s');
Wednesday, March 31, 2021
 
Angolao
answered 7 Months ago
72

Try this:

$tZone = new DateTimeZone("Europe/Amsterdam");
Saturday, May 29, 2021
 
mnagel
answered 5 Months ago
41

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;
Friday, June 4, 2021
 
Jesse
answered 5 Months ago
87

IMHO, existing answers do a poor job explaining the "Why" of this - focusing too much on reiterating what behaviour's valid. "access modifiers work on class level, and not on object level." - yes, but why?

The overarching concept here is that it's the programmer(s) designing, writing and maintaining a class who is(are) expected to understand the OO encapsulation desired and empowered to coordinate its implementation. So, if you're writing class X, you're encoding not just how an individual X x object can be used by code with access to it, but also how:

  • derived classes are able to interact with it (through optionally-pure virtual functions and/or protected access), and
  • distinct X objects cooperate to provide intended behaviours while honouring the post-conditions and invariants from your design.

It's not just the copy constructor either - a great many operations can involve two or more instances of your class: if you're comparing, adding/multiplying/dividing, copy-constructing, cloning, assigning etc. then it's often the case that you either simply must have access to private and/or protected data in the other object, or want it to allow a simpler, faster or generally better function implementation.

Specifically, these operations may want to take advantage of priviledged access to do things like:

  • (copy constructors) use a private member of the "rhs" (right hand side) object in an initialiser list, so that a member variable is itself copy-constructed instead of default-constructed (if even legal) then assigned too (again, if legal)
  • share resources - file handles, shared memory segments, shared_ptrs to reference data etc.
  • take ownership of things, e.g. auto_ptr<> "moves" ownership to the object under construction
  • copy private "cache", calibration, or state members needed to construct the new object in an optimally usable state without having to regenerate them from scratch
  • copy/access diagnostic/trace information kept in the object being copied that's not otherwise accessible through public APIs but might be used by some later exception object or logging (e.g. something about the time/circumstances when the "original" non-copy-constructed instance was constructed)
  • perform a more efficient copy of some data: e.g. objects may have e.g. an unordered_map member but publicly only expose begin() and end() iterators - with direct access to size() you could reserve capacity for faster copying; worse still if they only expose at() and insert() and otherwise throw....
  • copy references back to parent/coordination/management objects that might be unknown or write-only for the client code
Tuesday, June 15, 2021
 
turson
answered 4 Months ago
87

Events don't overload the += and -= operator. This is just hardcoded in the C# compiler which translates it into the add/remove methods of that event.

You can only overload + and - which then indirectly overload += and -=. If you overload + then automatically x += y becomes overloaded to x = x + y. So for your type you don't need to put in any extra work. Just overload + and you'll get += for free. This of course requires the left side argument and the result type being compatible, but that's usually the case.


The reason that you can't overload += separately is most likely that it creates strange semantics for reference types. If += modified the existing instance of the left side then the following code would behave strangely:

MyClass x=new MyClass();
MyClass y=x;
x+=SomeThing;
y has changed now too

On the other hand with += meaning x = x+y this code creates a new instance which it assigns to x. And the original instance remains unmodified in y;


In C++ on the other hand it is possible to safely specify a separate overload for += because you can overload the assignment and copy-constructor at the same time and use that to get the correct semantics.

Friday, July 30, 2021
 
rorymorris
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :