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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could if you reimplemented all your strings as objects.
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
is
For all intends and purposes it has the same functionality, just different syntax.