views:

48

answers:

1

Let's say for example I had a localised date class where the normal usage was to create an object.

$d = new Date(mktime(), 'MM-DD-YYYY', array('locale' => 'es'));

Now, what if I didn't want to always create a new object explicitly, but instead wanted something more along the lines of...

<p>The date is <?php echo 
Date::formatDate( mktime(), 'MM-DD-YYYY', array('locale'=>'es') );?>
</p>

In my formatDate method, would it be a good idea to invoke the constructor to internally create a date object, or should I completely make all internal method calls static?

class Date {
    function getLocalisedDate( $time, $format, $options ) {
        $obj = Date::Date(
            $time, $format, $options
        ); // invoke the constructor
        return $obj->get();
    }
};

I haven't developed many classes, I'm wondering if it's a common pattern in OO languages.

+2  A: 

The problem is in < php 5.3 the static method is always going to create an instance of the hard coded class. So if you are actually using MyAdvancedDate which extends Date youre always going to get an instance of the parent because self and __CLASS__ are always going to refer to the class the method is actually in. This is ofcourse unless you override the method explicitly in the descendent classes. This is called Late Static Binding.

When i need to implement LSB in 5.2 i generally make a static property and corresponding static accessors that allow me to change the class instantiated by static calls. The only thing here is this still assumes you are only ever going to use a single descedent as changing the static property will change it across the board. It can work in a punch though depending on what the actual architecture of the project/app/module/package.

prodigitalson
I'm aware that it will always create an instance, but it can't be that bad, can it? And I won't be extending this class either.
meder
No, as long as you are aware of that its fine. In fact its a common practice for implementing the factory methods, and singletons.
prodigitalson