Page 1 of 1

Placing a factory inside an abstract class (use of 'self')

Posted: Thu Jun 21, 2007 9:58 am
by Chris Corbyn
This is driving me nuts. I understand the problem, but is there a workaround before PHP6 introduces the 'static' keyword to do what I want?

Code: Select all

abstract class ORM {
    // ... snip ...
    public static function getInstance()
    {
        return new self(); //I've also tried __CLASS__ to no avail!!
    }
    
    public static function retrieveById($id)
    {
        $self = self::getInstance();
        $self->doSomeMagicWith($id);
        return $self;
    }
}

class User extends ORM {
    // ... snip ...
}

$user = User::retrieveById(112); //Get user #112
This give an error that I cannot instantiate the abstract class 'ORM'... fair enough, but I actually want to instantiate 'User', using a static method in the abstract class :( Any hints?

Posted: Thu Jun 21, 2007 10:42 am
by djot
-
What came to when thinking about your code ...

To instantiate User from within ORM will give an infinite loop. And even if it would work, you would overwrite the "outside" object with the "inner" one.

To instantiate ORM in ORM makes no sense, right?

djot
-

Posted: Thu Jun 21, 2007 11:08 am
by volka
djot wrote:To instantiate ORM in ORM makes no sense, right?
What's the problem with instantiating an object of a class in a static method of the same class?

@d11wtq: You coud pass an instance of ORM or a factory for ORM to the static method.

Code: Select all

abstract class ORM {
	public static function retrieveById(ORM $obj, $id) {
		$obj->doSomeMagicWith($id);
		return $obj;
	}
}

class User extends ORM {
	protected function doSomeMagicWith($id) {
		echo 'magic number: ', $id;
	}
}

$user = ORM::retrieveById(new User(), 112);

Posted: Thu Jun 21, 2007 12:32 pm
by Chris Corbyn
That's a nice solution thanks :) Exactly the clean workaround I was thinking of :)

~djot, I've not got the foggiest what you're talking about :P The method was a static method you you're in object context there... it would have worked fine if it created a "User" object rather than a ORM object.