Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Freek Van der Herten:
Method overloading is possible in PHP (sort of)
Oct 21, 2016 @ 14:33:41

Freek Van der Herten has a post to his site showing how PHP functions can (sort of) be overloaded with the help of a trait from Adam Wathan.

PHP does not support method overloading. In case you’ve never heard of method overloading, it means that the language can pick a method based on which parameters you’re using to call it. This is possible in many other programming languages like Java, C++.

However, with some clever coding, Adam Wathan made a trait, aptly called Overloadable, that makes method overloading possible. It works by just accepting any parameters using the splat operator and then determining which of the given functions must be called according to the given parameters.

He shows how to use the trait in a simple example, defining a single "bar" function and using the "Overloadable" trait to handle the switching between the methods based on the input variables. You can find more information about the trait and the source for it in this gist over on GitHub.

tagged: method overload trait custom splat operator variable

Link: https://murze.be/2016/10/method-overloading-possible-php-sort/

Lorna Mitchell:
PHP 5.6 and the Splat Operator
Mar 17, 2014 @ 14:05:36

Lorna Mitchell has a new post to her site looking at a feature of the upcoming PHP 5.6 release, the splat operator (three ellipsis...).

We have a couple of new features coming in to PHP 5.6 with names that sound much less exciting than the features they actually represent: "variadic functions" sound positively academic, and "argument unpacking" isn't exactly catchy. However they both use a new operator in PHP which looks like an elipsis (three dots ...) and is referred to as either the splat operator or the scatter operator. I included them in a recent version of my "Upgrading PHP" talk so I thought I'd share the examples here too in case anyone is interested.

She includes an example of it being used in a variadic function, one that lets you define an optional number of parameters without having to resort to func_get_args. She also talks about "argument unpacking" or the passing in of an array of values with the splat to have it handled like a string. An example with the mail function is included.

tagged: php56 splat operator variadic function argument unpacking

Link: http://www.lornajane.net/posts/2014/php-5-6-and-the-splat-operator


Trending Topics: