A few days ago Anthony Ferrara wrote down some thoughts on the future of PHP. I concur with most of his opinions, but not all of them. In this post I’ll focus on one particular aspect: Turning primitive types like strings or arrays into “pseudo-objects” by allowing to perform method calls on them.
Lets start off with a few examples of what this entails:
$str = "test foo bar";
$str->length(); // == strlen($str) == 12
$str->indexOf("foo") // == strpos($str, "foo") == 5
$str->split(" ") // == explode(" ", $str) == ["test", "foo", "bar"]
$str->slice(4, 3) // == substr($str, 4, 3) == "foo"
$array = ["test", "foo", "bar"];
$array->length() // == count($array) == 3
$array->join(" ") // == implode(" ", $array) == "test foo bar"
$array->slice(1, 2) // == array_slice($array, 1, 2) == ["foo", "bar"]
$array->flip() // == array_flip($array) == ["test" => 0, "foo" => 1, "bar" => 2]
Here $str is just a normal string and $array just a normal array - they aren’t objects. We just give them a bit of object-like behavior by allowing to call methods on them.
Note that this isn’t far off dreaming, but something that already exists right now. The scalar objects PHP extension allows you to define methods for the primitive PHP types.
The introduction of method-call support for primitive types comes with a number of advantages that I’ll outline in the following:
An opportunity for a cleaner API
The likely most common complaint you get to hear about PHP is the inconsistent and unclear naming of functions in the standard library, as well as the equally inconsistent and unclear order of parameters. Some typical examples:
// different naming conventions
strpos
str_replace
// totally unclear names
strcspn // STRing Complement SPaN
strpbrk // STRing Pointer BReaK
// inverted parameter order
strpos($haystack, $needle)
array_search($needle, $haystack)
While this issue is often overemphasized (we do have IDEs), it is hard to deny that the situation is rather suboptimal. It should also be noted that many functions exhibit problems that go beyond having a weird name. Often edge-case behaviors were not properly considered, thus creating the need to specially handle them in th
Truncated by Planet PHP, read more at the original (another 22926 bytes)
more
{ 0 comments... » Methods on primitive types in PHP read them below or add one }
Post a Comment