Click to See Complete Forum and Search --> : Creating Instances from Static Methods


jalfrezi
03-29-2007, 07:47 AM
Hi everyone,

Quite a difficult problem here. I need help confirming if this is a bug in PHP5 or not, as I think the following code produces an incorrect result. However, I am open to education if I have assumed that this result is false.

Basically, I have a base class which contains a static method. The static method should return an instance of the class. If I use the base class to extend from, I would assume that the static method would return an instance of the derived class, NOT an instance of the base class:


<?php

class BaseClass {

static public function fetch() {
return new self;
}
}


class ConcreteClass extends BaseClass {

private $title;

public function setTitle( $newTitle ) {
$this->title = $newTitle;
}
}


$c = ConcreteClass::fetch();
var_dump($c);
$c->setTitle('My Title');
?>

This results in $c containing an instance of BaseClass, not, as I assume, an instance of ConcreteClass.

Am I wrong here or is this a bug?

Cheers!

Jalf

dougal85
03-29-2007, 08:24 AM
http://bugs.php.net/bug.php?id=30934

Thread on php bugs on a similar note ^^

see bottom of article for explanation - i think its similar to what your asking

jalfrezi
03-29-2007, 08:53 AM
Thanks for that! This is exactly the same issue.

So, this is not a bug, eh? I would have thought that it was obvious what the expected behaviour of this would be, but I guess I'm wrong. I guess this really IS a feature, and that me expecting things to work in an obvious manner is what is at fault here.

This is stupid. This is clearly a case of optimisation before implementation: they haven't implemented this correctly prefering to opt for speed rather than completeness. Nice one. No wonder people see PHP as a joke.

Sorry for the rant, but as much as I love PHP, sometimes the dev's are so boneheaded. Sometimes they don't do PHP any favours!

Weedpacket
03-30-2007, 07:23 AM
I'm wondering how this would be done in, say, C#, which as far as I recall doesn't have anything with the semantics of PHP's "self". And of course you have to declare a return type for the fetch method.

I guess I'm wrong.You're wrong, because you've forgotten what "static" means. http://foldoc.org/foldoc/foldoc.cgi?static, http://foldoc.org/foldoc/foldoc.cgi?static+typing

jalfrezi
04-12-2007, 09:39 AM
@Weedpacket: You are 100% correct. Static typing is implemented at Compile time, not Run-time, hence why this isn't inherited as expected. Please ignore my bone-headed rant at PHP!

I'm gonna slink off and hid in my hole now.... :)

Piranha
04-12-2007, 09:44 AM
I just wonder why someone would like to do that instead of just creating a new ConcreteClass the normal way.

Weedpacket
04-13-2007, 11:41 PM
I'm gonna slink off and hid in my hole now....
I've heard tell that this early binding of self is to be addressed in PHP6 by adding a late-binding alternative.