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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With