Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Late Static Bindings in Wurst #977

Open
TheSkullbot opened this issue Dec 6, 2020 · 5 comments
Open

Late Static Bindings in Wurst #977

TheSkullbot opened this issue Dec 6, 2020 · 5 comments

Comments

@TheSkullbot
Copy link

TheSkullbot commented Dec 6, 2020

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.

@Frotty
Copy link
Member

Frotty commented Dec 6, 2020

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?

@peq
Copy link
Collaborator

peq commented Dec 6, 2020

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.

@TheSkullbot
Copy link
Author

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.

@Frotty
Copy link
Member

Frotty commented Dec 7, 2020

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.

@TheSkullbot
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants