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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

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

Post 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?
djot
Forum Contributor
Posts: 313
Joined: Wed Jan 14, 2004 10:21 am
Location: planet earth
Contact:

Post 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
-
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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);
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
Post Reply