7.9. Using Method Polymorphism
Problem
You want to execute different code depending on the number and type of arguments passed to a method.
Solution
PHP doesn’t support method polymorphism as a
built-in feature. However, you can emulate it using various
type-checking functions. The following combine( )
function uses is_numeric()
,
is_string()
, is_array()
, and
is_bool()
:
// combine() adds numbers, concatenates strings, merges arrays, // and ANDs bitwise and boolean arguments function combine($a, $b) { if (is_numeric($a) && is_numeric($b)) { return $a + $b; } if (is_string($a) && is_string($b)) { return "$a$b"; } if (is_array($a) && is_array($b)) { return array_merge($a, $b); } if (is_bool($a) && is_bool($b)) { return $a & $b; } return false; }
Discussion
Because PHP doesn’t allow you to declare a
variable’s type in a method prototype, it
can’t conditionally execute a different method based
on the method’s signature, as can Java and C++. You
can, instead, make one function and use a
switch
statement to manually recreate this
feature.
For example, PHP lets you edit
images using GD. It can be handy in an
image class to be able to pass in either the location of the image
(remote or local) or the handle PHP has assigned to an existing image
stream. Example 7-2 shows a
pc_Image
class that does just that.
Example 7-2. pc_Image class
class pc_Image { var $handle; function ImageCreate($image) { if (is_string($image)) { // simple file type guessing // grab file suffix $info = pathinfo($image); ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.