Do you know of any project that has redefined the native types of PHP as objects? Is it feasible?
Do you know of any project that has redefined the native types of PHP (string, array, ints, floats, bools, etc.) as objects? I'm not sure how feasible it would be but i was just thinking that it would be nice to have the native types as objects.
example:
$Name = new String('Mary had a little lamb.');
print($Name->Length); //pri开发者_运维问答nts 23
print($Name->Replace('/lamb/', 'duck')); // prints Mary had a little duck.
Would this add to much overhead? Have any thoughts on this?
There are many, many, many (even native) projects that are aiming at that - thing is: Nobody uses them.
There are basically two problems:
- PHP has only limited operator overloading. You can't overload the
+
operator. So to sum two number you would need to write$number->add($number2)
, which isn't quite intuitive. - PHP has loads of predefined functions. One could argue that PHP has the most powerful standard library of all programming languages. But: All those functions return the native types, not the boxed ones. So you would need to write something like
$number = new Number(function_returning_number());
. This also applies to 3rd party libraries.
For the first issue there is a PECL extension. It is not bundled with PHP though and is not enabled on normal PHP installations. So you can't use it for portable applications.
To solve the second issue, there is an Autoboxing RFC. Maybe it will be implemented, maybe not.
Perhaps someone can clarify this, as I'm not completely informed on the subject - but PHP runs on the Zend engine right (C++) and thus if you're proficient enough could probably implement your above idea.
精彩评论