I have defined a class foo which has a static method that returns an instance of class foo. It works, but is it considered good practice? Is it stupid? Will it blend?

<?
class foo {
	public $bar;
	function __construct() {
		$this->bar = 'bar is now defined';
	}

public static function fetch() {
	$r = new foo();
	return $r;
}
}
?>

you can use it thusly:

<?php

require_once 'foo.php';
$v = foo::fetch();

print_r($v);

?>

output:

foo Object ( [bar] => bar is now defined ) 

    There is nothing "wrong" about this and is quite common. For example, sometimes a "factory" will have static methods to create instances:

    $thingy = WidgetFactory::getInstance('foo');

    The singleton pattern often uses a static method to return instances of the class:

    $registry = &Registry::getInstance();

    Typically the static method is meant to replace the normal constructor..in which case the constructor method itself becomes private.

    So it can be done but you must ask why is this necessary for this class. It must have a reason that makes sense.

    http://en.wikipedia.org/wiki/Factory_design_pattern
    http://en.wikipedia.org/wiki/Singleton_pattern

      I definitely don't want a singleton. I may want several image instances defined at once. I'm not really sure I need a factory because I don't plan to subclass anything here. I just need an image class -- I won't be bothering with all manner of subclasses, etc.

      I just thought it was nice to be able to use one line of code:

      $img = Image::fetchTreeImage($db, TREE_ID);
      

      instead of two:

      $img = new Image($db);
      $img->fetchTreeImage(TREE_ID);
      

        Is there a reason you cannot do:

        $img = new Image($db, TREE_ID)
        

        ?

          I considered that, but was wondering how to handle the situation where the image did not yet exist vs. the situation where there are db records, an image file, etc. that already exist. In retrospect, I guess I could handle this by allowing optional arguments. if TREE_ID is supplied, the idea is to fetch an Image from the DB. If none is supplied, a new, blank image is created.

          Another issue is that an Image object can either belong to a node or the overall tree itself. Rather than writing additional subclasses like TreeImage and NodeImage (which just seems like a pain in the ass to me), I chose to have an objectType property of my Image class. This suggests to me that the factory approach might in fact be what I'm looking for, but I'm not really sure.

            Not being real clear on what you ultimately want to do, this is only a possibility, not really a suggestion; but perhaps what we're looking at here is a candidate for the decorator pattern, where the concrete decorators would support whatever is different between "node" and "tree" image objects?

              Write a Reply...