What fundamental objects are missing in Object Oriented PHP?
I've been coding with PHP for a while, and I've been relatively irritated at the inconsistencies in the procedural functions (especially Strings and Arrays).
With the support for objects, I've been wishing that PHP had a native implementation of Arrays and Strings as objects so that I could write code like:
$arr = new Array('foo', 'bar');
$item = $arr->pop();
Making an Array-like object isn't overly difficult, however, there's a significant performance hit. All it would end up being is a wrapper for the array constructs 开发者_Go百科anyway.
Are there other core objects that PHP should have for Object Oriented PHP?
EDIT to add:
This is NOT about how you can use arrays as objects; in fact, I specifically do not want the discussion of arrays in the answer, as that's not what the question is about. I used arrays as an example, and it seems no one read the question. I am interested in other classes/objects that should exist natively in core PHP.
Edit: It will be possible in PHP 6 with aoutoboxing is the automatic conversion the compiler makes between the primitive (basic) types and their corresponding object wrapper classes (eg, array and ArrayObject, double and Double, etc). There would be a special function named __autobox()
<?php
function __autobox($value) {
return ... /* some object */
}
?>
For Example :
function __autobox($value)
{
switch(gettype($value))
{
case 'integer':
return new MyIntegerObject($value);
break;
case 'array':
return new ArrayObject($value);
break;
default:
$stdObj = new stdClass();
$stdObj->value = $value;
return $stdObj;
break;
}
}
Example using:
var_dump(5 == new MyInteger(5));
bool(true)
You could argue that PHP should convert or at least extend some of it's natives into an object equivalent and from an ease of use point of view you are right but SPL offers most of the things we need so nobody is really complaining. The way we work with arrays is flexible enough and doesn't consume unnecessary memory.
If I had to choose i'd rather have PHP streamline it's array api instead of just converting all arrays into objects. Why is it array_map and asort? Why not array_sort for example. It'd rather have them fix that in php6 and actually had the chance to ask Scott McVicar and Derick Rethans a few months ago and they responded that it would break backwards compatibility and anger the large userbase. Dumb answer but end of story i'm afraid.
But to answer your question, no ... i don't think PHP should adopt it's primitive types as language objects.
精彩评论