Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#-like extension methods in PHP?

Tags:

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?

like image 782
caesay Avatar asked Jul 28 '10 02:07

caesay


2 Answers

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.

like image 72
deceze Avatar answered Sep 17 '22 18:09

deceze


Since PHP 5.4 there are traits which can be used as extension methods.

Example:

<?php trait HelloWorld {     public function sayHelloWorld() {         echo 'Hello World';     } }  class MyHelloWorld {     use HelloWorld;     public function sayExclamationMark() {         echo '!';     } }  $o = new MyHelloWorld(); $o->sayHelloWorld(); $o->sayExclamationMark(); ?>  

result:

Hello World! 

Once You include a trait to a class, lets call it for example with a name Extension, You can add any methods You want and locate them elsewhere. Then in that example the use Extension becomes just one-time decoration for the extendable classes.

like image 31
Roland Pihlakas Avatar answered Sep 18 '22 18:09

Roland Pihlakas