.
OOP coding query - Grin with cat attached
Previous Entry Next Entry
OOP coding query Jan. 4th, 2007 05:24 pm
PHP, with a flamboyant disregard for static/dynamic separation, allows me to do the following:

class thingy{
static function boo() { print('BOO'); }

function bang() { print('BANG'); }
}

$myThing=new thingy();
thingy::bang();
$myThing->boo();

ie, it makes no effort to stop me calling static functions (or members) in a dynamic (and probably misleading) fashion. I'd expect $myThing->boo() to throw a (probably fatal) error saying something like "Static method called dynamically". Without this protection, I'd suspect that allocations to a static variable from inside an object would cause changes not merely within the object scope, but within all objects *and* the class scope, which feels like a world-class "gotcha" waiting to happen.


Is this common among OOP languages, or is this just another example of PHP's juvenile status?

From: topbit
Date: January 4th, 2007 - 05:38 pm (Link)
Seems pretty reasonable to me - how else would you have a factory pattern and then use the instantiated object?
From: wechsler
Date: January 4th, 2007 - 05:42 pm (Link)
ok, I should have actually finished asking the question before I hit post - lemme go fix that!
From: duncanneko
Date: January 4th, 2007 - 05:50 pm (Link)
Java will warn but let you do object.staticfunction ($myThing->boo()) with "you should use the static class name here" as it's confusing but safe.

It will point-blank refuse to let you do classname.dynamicfunction (thingy::bang()) - how does PHP get around the non-existence of local dynamic fields at that point? Or does that create an implicit object?
From: topbit
Date: January 4th, 2007 - 07:56 pm (Link)
If you try to use a this-> variable, it will complain. You can, in a static instance, use self:: for static variables.
From: mooism
Date: January 4th, 2007 - 06:21 pm (Link)
$myThing->boo() works under all OO languages I've encountered.

thingy::bang() wouldn't work under any language I've used. Does PHP not give a runtime error?
From: ciphergoth
Date: January 5th, 2007 - 10:37 am (Link)
$myThing->boo(...) can be handy because it still does dynamic dispatch. Obviously thingy::bang() should throw a run-time error - I'm guessing that PHP doesn't track enough information at compile time to check then.