Question

In PHP, I have a class with a static method:

class Foo {
   public static function bar($arg1, $arg2, $arg3) {
        //logic here
   }
}

I want to create an alias of the static method called star() for backwards compatibility. It is called the same way:

 Foo::star('a', 'b', 'c');

What is the best way to do this? I'd prefer if I can change the number of parameters or order of bar() this change automatically propagates to star() as well.

Était-ce utile?

La solution

public static function star()
{
    return call_user_func_array(array('Foo', 'bar'), func_get_args());
}

References:

Autres conseils

The short (and fun!) answer to your question is to store your function in a trait then alias the function when you import the trait. This will ensure both functions have the same method signature.

// Tested on PHP 5.4.16
trait BarTrait
{
    public static function bar($arg1, $arg2, $arg3) {
        echo $arg1, $arg2, $arg3, "\n";
    }
}

class TestClass
{
    use BarTrait { bar as star; }
}
TestClass::bar(1, 2, 3);
TestClass::star(1, 2, 3);

The long answer is that I don't think there's any reason that you would ever need to change the function signature for the star() method.

If you are keeping the star() method, it is because you either have an API that you don't want to break, or you have too many call-sites to fix in the short-term.

In both cases, the only way to safely add more parameters to the star() method would be to use optional parameters, i.e. star($arg1, $arg2, $arg3, $arg4 = null, $arg5 = null) This would mean that bar() would need to have optional parameters as well.

And if bar() has optional parms, then again there is no need to change the method signature of star().

You simply let star() call-through to bar() with the non-optional parameters:

class Foo {
    public static function bar($arg1, $arg2, $arg3, $arg4 = null, $arg5 = null) {
        //logic here
    }
    public static function star($arg1, $arg2, $arg3) {
        return static::bar($arg1, $arg2, $arg3);
    }
}

Any call to star() that you would modify to use the new parameters can just as easily be modified to call far() instead.

If you have a case where you really would need to change the signature of star() I would be interested in hearing more about it.

-D

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top