WurstScript icon indicating copy to clipboard operation
WurstScript copied to clipboard

Late Static Bindings in Wurst

Open TheSkullbot opened this issue 5 years ago • 5 comments

Is your feature request related to a problem? Please describe. Unless I'm missing something, it's not possible to access a child static member/method from the parent class. Overriding may do the trick for methods but not for (static) attributes.

Describe the solution you'd like In PHP (yes, again) you can use the static keyword to reference the child class name in the parent class :

class A 
{
    static $member = "Something";

    public static function test() 
    {
        static::$member; // <= Late Static Binding
    }
}

class B extends A 
{
    static $member = "Something else";
}

A::test(); // Prints "Something"
B::test(); // Prints "Something else"

I've no idea if it's possible in the current state/workflow of Wurst though.

TheSkullbot avatar Dec 06 '20 00:12 TheSkullbot

Static functions are just regular functions that are put into the class namespace, there is no dispatch for them. Why would you wanna do this in first place, why not use a closure instead?

Frotty avatar Dec 06 '20 12:12 Frotty

If you want to reuse the test function for class A and B you could put it into a Wurst module. Another approach might be the Singleton pattern.

I don't think it's worth it to add this as an additional feature to the language.

peq avatar Dec 06 '20 12:12 peq

I've updated the code with a member usage instead of a method, which is closer to what I want to achieve. Basically, I want the test method to be able to use the static $member value from the child class, without having to redefine the method in each child class.

TheSkullbot avatar Dec 06 '20 14:12 TheSkullbot

Seems like a less readable and obvious way to override something - I still don't really see a benefit. If you want to set a variable depending on subtype without overriding a getter, you could simply make it a non-static variable and set it in the constructor e.g.

Frotty avatar Dec 07 '20 10:12 Frotty

In PHP, it's mainly used for Active Record-based models and Factory patterns.

abstract class A 
{   
    static function create() 
    {
        return new static();
    }   
}

class B extends A
{
   // Specific stuff
}

$obj = B::create(); // Instanciate B object

TheSkullbot avatar Dec 07 '20 11:12 TheSkullbot