2

I am defining a class which has a DateTime object as one of the properties. I want to set its default value to unix timestamp of '-1'. I also want this default value to be constant so that all objects know its value.

But I do not want to declare something like const PROPERTY_DEFAULT_DATE = '-1'; as the property will be a DateTime object and operations/functions using this default value and the property will be difficult to handle if PROPERTY_DEFAULT_DATE is not a proper DateTime object

So, can I have particular object instance of a class as constant inside another class?


The PHP manual says

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

Doesn't mention about this, but I think it can't be done (tried lot of variations, always got syntax errors)
If it's not possible, what alternatives do I have?


Edit : I think I need to find the solution to the problem of defining a "Default Value" to my property, which in this case happens to be a DateTime object.
What default value will you set in the __construct()? (no, not NULL please, I expect something more elegant solution must exist) Also keep in mind that it may be used in operations/functions inside the class/subclass
Update : I followed the advice here and created a private $_DEFAULT_DATE property and a getter for it. There is no setter for this property, so I can be assured that it'll not be changed. (Of course, I take care not to change it within class implementation)
wadkar
  • 960
  • 2
  • 15
  • 29
  • an aside, but are you using PHP's DateTime class or writing your own? I'm pretty sure (but I could be wrong) that DateTime won't let you set it to unix timestamp=-1. – dnagirl Sep 06 '11 at 15:03
  • perhaps you are wrong, try `$nullDate = new DateTime('@-1')`; or am I supressing the warnings/errors by using @? – wadkar Sep 06 '11 at 15:06
  • you're suppressing the error, which you actually don't need to do since DateTime does it automatically. I checked my assumptions and I am correct: -1 is an illegal value. Try the following- `$d=new DateTime();//now $u=new DateTime('-1');//ignores the illegal value and returns new DateTime(), ie now $u1=date_create('-1');//ignores the illegal value and returns new DateTime(), ie now $u2=date_create_from_format('U',0);//time=0 $u3=date_create_from_format('U',-1); //returns false` – dnagirl Sep 06 '11 at 16:20
  • I am using PHP5.3 , and I don't get any errors, and I get timestamp of -1, i.e. ( unix epoch - 1 second ) . Even if I leave the @, I get same results. Moreover, the @ is inside the quote, i.e. it is part of the string argument passed to DateTime. I think DateTime takes argument starting with @ to be unix timestamp (as it throws error if you pass integers, try `new DateTime(32)` or `new DateTime('32')`) but if you append it with @ , the argument is a string now, but DateTime creates object with dateTime = timestamp value after the @ – wadkar Sep 06 '11 at 18:56

4 Answers4

3

Well, unfortunately, the manual is right. You cannot put an object in a constant. You can make it a property, or in your case a static function might be suited;

YourClass::getDefaultDate(); // return DateTime('-1');
Rijk
  • 11,032
  • 3
  • 30
  • 45
1

It's not possible. The simplest alternative is to use a static property, but it sounds like you want to make sure this property does not change.

So in that case the only logical way to do this, is by making the static property private, and add a static function that returns the DateTime object.

However, I still don't think you want to use a singular object. If any other method requests this default object they'll be able to modify it and you might get weird results. Any request to this method (in my mind) should receive a new or cloned DateTime object.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • hmm, if you were to use a DateTime object as property, what value would _you_ set it to in the `__construct()` ? – wadkar Sep 06 '11 at 15:07
  • @Sudhi: PHP's DateTime class defaults to now on construction. – dnagirl Sep 06 '11 at 16:27
  • yes, I know. But would you rather set it as now() or something else? DateTime('0000-00-00 00:00:00') produces weird result, and trying DateTime('@-1') isn't working in this case. I wonder if its more of convention issue than a standardization issue – wadkar Sep 06 '11 at 18:25
0

The manual is correct: no, you can't use objects in const expressions in PHP.

You have to initialize a proper member inside a constructor if you want to use it this way. If you want it to be unalterable, with certain effort you can make it so.

Community
  • 1
  • 1
sanmai
  • 29,083
  • 12
  • 64
  • 76
0

from php.net about sonstant syntax and use Someone spoke about "dynamic" assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work only with variables. Let's take the proposed example:

<?php 
/** 
 * Constants that deal only with the database 
 */ 
class DbConstant extends aClassConstant { 
    protected $host = 'localhost'; 
    protected $user = 'user'; 
    protected $password = 'pass'; 
    protected $database = 'db'; 
    protected $time; 
    function __construct() { 
        $this->time = time() + 1; // dynamic assignment 
    } 
} 
?> 

Those aren't constants, those are properties of the class. Something like "this->time = time()" would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.

Conclusion: Don't try to reinvent constants as variables. If constants don't work, just use variables. Then you don't need to reinvent methods to achieve things for what is already there.

From self: you can use private static methods and use magic methods __getStatic (since it's avaliablr only from php 5.3) or use simple __get and property_exist or use Reflection. But actually I don't see the problem which need this solution. Sorry ((

ZigZag
  • 539
  • 1
  • 8
  • 19
  • I _am_ defining a constant : '-1', but within the context of unix timestamp . Is it not a constant then? – wadkar Sep 06 '11 at 15:17
  • if I had, I wouldn't be asking this question. When I said _constant_ I meant in terms of value of the property/attribute. It is not going to change ever. Just as literal '-1' as int will be same (and hence a constant) in any language/code, I want '-1' as constant : but in the context of unix time stamp (as in 1969-12-31 23:59:59 +00:00) . I just as well use '0' (so I get exactly unix epoch) , but the point is, its a definite and constant mark in the timeline. – wadkar Sep 06 '11 at 18:50