caesay caesay - 2 months ago 6x
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";

or even


Is there a way to have similar behavior in PHP?


You could if you reimplemented all your strings as objects.

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

$str = new MyString('Bar');

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



my_extension("hello", "another");

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