Abstract trait't method can't be static in PHP?

Here's my example:

trait FileConfig {
    public static function getPathForUploads() {
        $paths = static::getPaths();
        //etc.
    }

    abstract public static function getPaths(); //doesn't work. Error: "Static function SharedDefaultConfig::getPaths() should not be abstract"

    abstract public function getPaths(); //OK
    public static function getPaths() {} //OK
}

      

Class:

class AppConfig {
    use FileConfig;

    public static function getPaths() {
        return array(...);  
    }
}

      

Call:

AppConfig::getPathForUploads();

      

You need to make it static and abstract (to force the classes to use FileConfig to implement getPaths ).

I wonder how one can implement a method that changes its static property ? Is this good practice or are there better solutions? Will it one day become illegal?

thank

+3


source to share


3 answers


This is fixed in php 7, so the following code works:

<?php

error_reporting(-1);

trait FileConfig {
    public static function getPathForUploads() {
        echo static::getPaths();
    }

    abstract static function getPaths();
}

class AppConfig {
    use FileConfig;

    protected static function getPaths() {
        return "hello world";
    }
}

AppConfig::getPathForUploads();

      



http://sandbox.onlinephpfunctions.com/code/610f3140b056f3c3e8defb84e6b57ae61fbafbc9

But it doesn't actually check if the method in AppConfig is static or not at compile time. You will only get a warning when you call a non-static method statically: http://sandbox.onlinephpfunctions.com/code/1252f81af34f71e901994af2531104d70024a685

+4


source


You don't need to make the method static to force the classes to use it to implement the method. You can just use interfaces side by side.

trait FileUploadConfig {
    public static function getPathForUploads() {
        $paths = static::getPaths();
        //etc.
    }
}

      

The mark remained as it is. I just removed the functions for the interface.



interface PathConfiguration {
    public static function getPaths();
}

      

The interface forces the class to implement the function. I left there static

to match the specification of the signs

class AppConfig implements PathConfiguration {
    use FileUploadConfig;
    public static function getPaths() {
        return [];
    }
}

      

+3


source


To force classes using FileConfig to implement getPaths, you don't need to make the abstract static function. Static means that it belongs to the class that declared it. Make it protected statics, add code from the property, and then you can change the inheritance behavior from your AppConfig class.

+2


source







All Articles