5

Let's say I have a class in PHP with a method that serialises data. Being English, I use the English spelling of -ISE.

class Foo
{

    public function serialise($data)
    {
        return json_encode($data);
    }

}

Let's also say that I have an American developer on my team who tries to "serialize" the data (-IZE).

$foo = new Foo();
$foo->serialize(['one', 'two', 'three']);
// PHP Fatal error: Uncaught Error: Call to undefined method Foo::serialize()

The obvious way to solve this is to alias the method. My instincts are to create another method with the American spelling and simply pass the same parameters.

class Foo
{

    // ...

    public function serialize($data)
    {
        return $this->serialise($data);
    }

}

But this has a couple of downfalls:

  • I have to match the parameters and remember to update both methods if there's ever an update (error prone).
  • Additional function call for American developers means the code is less efficient.
  • Modifying one in a sub-class doesn't necessarily update the other.

My question is: is there a better way to alias a class method in PHP? A way that can get around the concerns that I have?

James Long
  • 4,437
  • 1
  • 18
  • 30

1 Answers1

2

One way to reduce the maintenance burden is to use the ... operator to accept any number of arguments, and unpack them in the forwarded call:

public function serialize(...$args)
{
    return $this->serialise(...$args);
}

The downside is that the function now no longer has a signature which can be auto-completed in editors; you could list the real arguments in a docblock, but that would defeat the point because you'd need to keep it up to date.

The best solution though is probably to have a naming convention, and have everyone learn it, for the same reason as any other coding convention: it's a lot easier to read code which is consistent. Using a good editor or IDE, the wrong spelling will quickly be highlighted and corrected, and there is no additional complexity of maintaining the aliases.

IMSoP
  • 77,988
  • 8
  • 99
  • 149
  • Interfaces can help a lot toward naming conventions. Especially when the IDE can automatically add stubs for required methods. – cautionbug Nov 03 '20 at 17:37