caesay caesay - 3 months ago 23
C# Question

C#-like extension methods in PHP?

I like the way in C# where you can write an extension method, and then do things like this:

string ourString = "hello";
ourString.MyExtension("another");


or even

"hello".MyExtention("another");


Is there a way to have similar behavior in PHP?

Answer

You could if you reimplemented all your strings as objects.

class MyString {
    ...
    function foo () { ... }
}

$str = new MyString('Bar');
$str->foo('baz');

But you really wouldn't want to do this. PHP simply isn't an object oriented language at its core, strings are just primitive types and have no methods.

The 'Bar'->foo('baz') syntax is impossible to achieve in PHP without extending the core engine (which is not something you want to get into either, at least not for this purpose :)).


There's also nothing about extending the functionality of an object that makes it inherently better than simply writing a new function which accepts a primitive. In other words, the PHP equivalent to

"hello".MyExtention("another");

is

my_extension("hello", "another");

For all intends and purposes it has the same functionality, just different syntax.

Comments