What are the main objects missing in object oriented PHP?

I programmed PHP for a while, and I was annoyed by inconsistency in procedural functions (especially Strings and Arrays).

With object support, I wanted PHP to have its own implementation of arrays and strings as objects, so that I could write code like:

$arr = new Array('foo', 'bar'); $item = $arr->pop(); 

Creating an object matched by an array is not too difficult, however, there is considerable success. All this will ultimately be a wrapper for array constructions anyway.

Are there any other basic 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 to discuss arrays in the answer, since this is not a question. I used arrays as an example, and nobody seemed to read the question. I am interested in other classes / objects that should exist primarily in PHP.

+4
source share
2 answers

Edit: This is possible in PHP 6 with aoutoboxing is an automatic conversion that the compiler does between the primitive (base) types and the corresponding classes of object wrappers (e.g. array and ArrayObject, double and Double, etc.). There will be a special function called __autobox ()

  <?php function __autobox($value) { return ... /* some object */ } ?> 

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; } } 

Usage example:

 var_dump(5 == new MyInteger(5)); bool(true) 
+2
source

You could argue that PHP should convert, or at least distribute some of its natives into an object equivalent, and you are right in terms of ease of use, but SPL offers most of the things we need, so no one complains. The way to work with arrays is quite flexible and does not require unnecessary memory.

If I had to choose, I would prefer PHP to simplify its api array, rather than just converting all arrays into objects. Why is it array_map and asort? Why not array_sort, for example. Most likely they would fix it in php6 and actually had the opportunity to ask Scott McVicar and Derick Retans a few months ago, and they replied that it would violate the compatibility and anger of a large user base. Dumb answer, but I'm afraid of the end of the story.

But to answer your question, no ... I do not think that PHP should accept its primitive types as language objects.

+2
source

Source: https://habr.com/ru/post/1341038/


All Articles