Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

  1. Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")
  2. Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")
  3. Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")
  4. Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")
  5. Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

share

locked by World Engineer Feb 23 at 1:43

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

closed as not constructive by Thomas Owens, Walter, Mark Trapp Sep 24 '11 at 7:47

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

9  
@Stan: Much as you'd like to avoid that kind of comment, you're going to get it anyway. The problems people have with PHP are largely in the categories of things you're ruling out in your post. [...] –  Fishtoaster Dec 19 '10 at 0:56
24  
[...] You're saying "How can we improve the experience of getting hit in the face without actually not hitting you in the face?" I mean, yes, getting free coffee while we're being hit in the face might be nice, it doesn't really address a lot of the underlying problems with, well, being hit in the face. So, while I hope you get some useful answers here (as there already appear to be), don't be surprised by unproductive ones. –  Fishtoaster Dec 19 '10 at 0:59
5  
@Fishtoaster: if PHP associates with being hit in the face for you, by all means keep away from it. You are most definitely not interested in improving it. It so happens though there are people who are. This topic is for them, not for you. I'm sure this site has a lot of topics for you too, this is just not one of them. –  StasM Dec 19 '10 at 7:57
5  
I'm using getting hit in the face as an example- a situation where superficial improvements aren't that important; when most people's problems are with the underlying thing. I'm not even knocking your attempt to get suggestions for those superficial improvements- I'm just pointing out why you're likely to get a few unhelpful answers, given the situation. –  Fishtoaster Dec 19 '10 at 8:23
6  
@Fishtoaster: Not everyone, surprisingly, hates PHP - I have always liked it. Very flexible and quick (to code). –  Orbling Dec 19 '10 at 14:52

64 Answers 64

Faster function calling

We have call_user_func($f,$a1,$aN), but it's been superseded with $f($a1,$aN). However, there's no such thing for call_user_func_array($f,$args).

My proposal is to create a specific language syntax for this, such as $f{$args}. The reason everyone should stay a mile away from call_user_func* is that they're extremely slow and ugly looking in the sense that there are better alternatives.

Object decleration syntax

Right now, to create an object on the fly, you need: (object)array('prop'=>'value');. By convention, we should also have object('prop'=>'value');. Also, short syntaxes would be handy, similar to JSON.

A be-all-end-all magic method for types

Right now, we have __toString(), and many suggested __toInt/__toFloat/etc. My advice would be to implement __toType() or __typecast(), which as a first parameter, the desired data type is passed, eg:

class Test {
    public function __toType($type){
        switch($type){
            case 'integer':
                return (int)$this->age;
            case 'string':
                return $this->age.' years';
            default:
                throw new EUnsupportedTypeException();
        }
    }
}

If we wanted to be more specific, we could add another argument after $type, namely $class. So you can: if($class=='person')return new Person($this->age);

Specifying Data Type in foreach

Currently, you can specify the data type of a PHP function argument, like so:

public function say_hello_to(UserClass $user){
    $this->say('Hello, '.$user->name.'!');
}

It would be great to do this in a foreach as well:

public function on_enter_office(){
    foreach($users as UserClass $user) // <- See UserClass here?
        $user>say_hello_to($this);
}

The current "fix" is using a closure, like so:

public function on_enter_office(){
    $users->each(function(UserClass $user){
        $user>say_hello_to($this);
    });
}

The fix takes more resources, more writing and messes the scope, hence why a native solution will make it easier, cleaner and probably faster than the current fix.

Conditional Defines

This probably won't be a useful feature for many people, but it is a great way to keep the running code at a minimum even when it is compatible with old systems, making execution faster. Consider the following code:

if(!function_exists('json_encode')){ function json_encode($value, $options=0){ // legacy code } }

  • The // legacy code section is still parsed, hence any errors in there will cause PHP to quit.
  • Parsing it also makes PHP slower, even if it doesn't need it at all.
  • The code is not intuitive to developers
  • Any IDE parsing engines will get confused since they ignore if statements and end up listing the function twice.

The fix? Conditional compilation:

#if PHP_VERSION<5.2
function json_encode($value, $options=0){
    // legacy code
}
#endif
share

Bring taint support up to latest version and include it in standard builds, preferably turned on in the default config http://wiki.php.net/rfc/taint

This would prevent XSS and SQL injection attacks by making people code properly.

share

Make strings object like, with built in methods to replace the inconsistently named and parametered non-object ones. e.g.

$subject->replace($search,$replace);
$string->split($separator);
$string->trim();

etc.

Edit: one more thing: These methods should always expect and emit UTF-8, except for ones specifically intended to deal with encodings. If input is invalid UTF-8, an exception should be thrown, even if the output of the function wouldn't be affected by the encoding.

share
1  
subject->verb(object), makes parameter order easier to remember. –  SHiNKiROU Dec 30 '10 at 4:09
2  
So what would is_object($string) return? This would either break backwards compatibility big time, or result in the introduction of really unintuitive almost-but-not-quite-objects. –  Tgr Apr 16 '11 at 16:37

Make PHP truly object oriented. The slap on another global function evolution of PHP needs to end.

array_merge(array_filter(array_intersect_key($arr1, $arr2), "is_int"), $arr3);

This is hard for me to read. I have to make my own mental stack and sort of compile it myself. Basically it should read in the reverse. $dog->wakeup()->bark(); is easy to read compared to bark(wakeup($dog))

$arr1->array_intersect_key($arr2)->array_filter("is_int")->array_merge($arr3);

You've made the step towards enabling object/method support now please use it in actual core PHP functions.

Let's rename 500 functions and change parameter order for them.

Shifting this functionality to methods would enable them to be renamed using some consistently. Would it break any backwards compatibility if strings and arrays had their own methods?

share
3  
I think array not being an object type is a big mistake in PHP. Leads to all kinds of trouble. Unfortunately, it's an evolutionary thing. You can do what you want here with extension or userspace though. Would probably fit SPL well. –  StasM Dec 18 '10 at 17:24
3  
The same argument applies to strings. I'm just referring to the lack of methods in general. Languages like Java, Python, C# etc all have much more readable code. I guess you are looking for features, but fixing what is IMO broken would be a better pay off. –  Keyo Dec 18 '10 at 17:28
6  
No, don't be silly. It'd be dog_wake_up($dog); bark_dog($dog); –  Matchu Dec 24 '10 at 18:24
2  
IMHO, any new string methods should expect and emit UTF-8, and throw exceptions if the input is not valid UTF-8. This would greatly reduce the need for a major reworking of unicode support. –  rjmunro Jan 6 '11 at 23:39
1  
@luiscubal No. An extra parameter will mean that we can't add parameters later if we invent new things to add to the function. For example, if $string=>trim() only did whitespace (like before 4.1.0), then your system would say $string=>trim('ISO-8859-1') trimmed whitespace from ISO-8859-1 strings. If we then wanted to be able to trim stuff that wasn't whitespace, we'd be unable to add the parameter for that, unless we make people specify the encoding first. We should be encouraging people to believe that any text anywhere that is not UTF-8 is wrong. –  rjmunro Apr 17 '11 at 0:00

My number one feature would be

operators overloading

In my opinion, one recurring feature asked for here, namely native types as objects, can be fixed by creating your own wrapper classes. I have developed for my projects an arrayData object, a stringData object, an intData object, and so on... This solves:

  • Strong typing: since those are custom classes, they can be enforced
  • Type overloading: I can add whatever methods I need to my arrayData class
  • Type conversion: each of my classes has ->toArray(), ->toInt(), ->__toString() methods, and so on
  • html escaping in templates (strings are userStringData class that extends stringData class).
  • values are always passed by reference unless instructed otherwise
  • creating an intData('string') throws an exception.
  • etc (the list of benefits is still extremely long)

Imho, this is more beneficial than native types as objects, since you can have the exact number of methods you need, and call them to your liking.

But what I miss oh so much is the ability to use native operators on my objects. I am able to use the [] operator thanks to arrayAccess. But I can't use "+", "-", etc. If I could, then I could do stringData + stringData (equivalent to $string.$string), or stringData-stringData (equivalent to str_replace($str,'', $string)), or compare my types with ">" and "<="...
My current implementation uses $intData->add($n), $intData->substract($n), and so on. Cumbersome, specially in functions where you could expect either a native int or an intData object. Which means I have to check with instanceOf inside each function.

In other words, although my classes are ready, optimized and nice, until I can overload operators, they are not much more than a proof of concept. Using them in an actual project is annoying.

share

Expose zval reference count. (Yeah, we could use xdebug_debug_zval, but enabling Xdebug on a live site, ick.) Use case: active record object store - you have models which correspond to external resources (like database rows), and are responsible for modifying those resources. Having two separate object representations for the same resource would be bad (data loss due to conflicting writes and so on), so we need some sort of cache which can return the model for the requested resource if it has been loaded already. That would kill garbage collection, however: a last reference to the model object would always remain in the cache, so iterating through a large set of resources like a big DB query or a large directory would quickly eat up memory. This could be avoided if the object store could be check whether there is only a single reference to the stored object (the store itself) and destroy it if that is the case.

share
1  
@StasM: how about weak references? That is a feature supported by a lot of languages, seems easy to implement, and makes it trivial to create an object store whose contents can be garbage collected. –  Tgr Apr 20 '11 at 10:11

Large file support. Pretty please?

See http://bugs.php.net/bug.php?id=27792 (though there may be more areas/functions that need attention as well).

share
  1. I'd one day like to see data type, however -- I also like the simplicty of not having to deal with data types, this is a double edged sword for me.
  2. namespaces!
  3. Overload function calls with different method signatures
  4. Better support for unit testing and code injection, PHPUnit is an amazing tool, as well Symfony code injection framework does wonders... however they all come with their own learning curve.
share
1  
4. better in what way? –  StasM Dec 17 '10 at 21:20

I need some erlang features in php:

  • hot code loading
  • atoms
  • pattern matching (include name of functions, matching statement like: case of)

Working with bytecode: saving, loading, removing and so on...

Flexible embedding system

share
  1. Let scalars be treated like objects. If I try to do $scalar->toLower(); why tell me I'm wrong? Why not just temporarily cast it to something like a "Scalar" object type and then move to "undefined method" (perhaps not do this as null)?

  2. Remove resources from userspace. PHP has objects now. Everything that's a resource now can be in a object wrapper that hides it as a private property. Functionality may need to be added for __sleep() and __wakeup(). Most resources can be easily recreated in a "similar" state. Even if they can't, the PDO object can't be serialized: I assume the same can be done with other objects.

  3. Let the actual PHP community make votes with their code: allow us to redefine existing methods, classes, and functions. Bad code will rot, just like it does in Javascript. It'll let the people using PHP figure out what they need instead of needing to guess all of the time. The functions and functionality used/overridden the most likely needs to be considered.

    This also has the side-effect of involing the PHP community with the UTF (hopefully UTF-8) issues. Instead of having a system-wide setting that turns unicode on or off, PHP developers can override the functionality they need for just their application.

  4. Make _ an implcit namespace separator. People have been using it since PHP5, let people build off their code instead of rewriting if for PHP 5.3. I don't know the complexities of it. I know there's initially some thought about code that does class names like Zend_Exception: Allow it, the developer will always have to access it as Zend_Exception or \Zend\Exception and never Exception. Treat it as a full name instead of just part of one.

  5. OOP: take some hints from Javascript/Actionscript/Python. Traits look promising, but changing type dynamically at runtime would be awesome.

  6. Properties: I see talks are in the works about properties, please implement them dynamically. PHP is supposed to be a dynamic language. We should be able to define properties (just about everything) at runtime.

  7. Treat constants as what their used for: global variables. Classes/Functions/Namespaces all fit this bill. Maybe when everyone starts realizing that they're all globals right now there will be more ideas to fix the issue of there being so many global variables/constants.

  8. JIT-compiling: Javascript can do it and be super-fast. PHP is one of the few ones behind in this one.

  9. PHP is supposed to be optimized for "Hypertext", yet there's no easy way to escape output as such. Personally, I'd redefine the 'print' to do an htmlspecialchars(). Overall, it may just need to be a printh or echoh.

  10. Simplify php.ini. php.ini is for System Administrators, not developers. Remove the incompatibilities of short tags, fix them, or remove them. Its annoying for system administrators to be able to turn features of the language on/off for the entire system. And work around them when trying to distribute software.

  11. Allow PHP developer to exist after a request cycle ends (for FastCGI and Apache). Expose this over an API. Allow the system administrator to disable or limit this. (Require the php program to return control to the dispatcher within 10 seconds or it loses its persistant status).

  12. Make PHP a general programming language. <?php tags are annoying: make it not required when you detect a !#/...

  13. Shortand for creating objects {} and arrays[], Taje a look at PiHiPi, they implement this and a lot of other simple syntactical sugars.

    14: Allow [] to access properties and functions on objects. Functions and Classes are first-class citizens now, right? Make [] the de-facto way (like javascript/actionscript) for accessing things dynamically on objects.

  14. Allow PHP code to be PHP modules. I shouldn't have to learn C just to make my library available system-wide in multiple processes. Let the PHP community figure this one out more.

  15. Instead of taking ideas from Java/C, take them more from dynamic languages like Javascript, Actionscript, and Python. More specific functionality is listed below.

  16. Fatal Errors: why are most errors still not recoverable? I love the notion of logging errors in a log file (implemented at a very high level). What I don't like is always hearing about a "white page". I do a lot of checks and declarations in my code to avoid these: but when someone passes a null instead of an object to my function, god forbid that PHP can recover from such a catastrophic without making me do an is_null() myself. Sure its an error, it just seems silly that most other languages call this a NullReferenceError/Exception that can be dealt with and presented with more than just a white screen.

    At the very least, stop adding fatal errors. I have the ability to upgrade a lot of servers running PHP 5.2, but I can't: because I don't have time to go through ~200 sites on each server to fix the old code. The less new fatal errors you add, the more likely you can get people on board with new versions of PHP.

    Remove as many fatal errors from the language as possible. PHP is supposed to be a dynamic language: why can every other language recover from most errors PHP considers fatal? Programmers can work around errors, but not if the program forcibly dies after what most languages consider a NullReferenceException.

  17. Make exceptions resumable. So we can more easily intermix exceptions and errors.

  18. (The most time-consuming and unlikely) Separate out the language-discussion, API/module discussion, and the interpreter discussion. They shouldn't be so integrated like right now. Issues with the current interpreter should be figured out last. Pypy/Parrot/JVM all support multiple languages. V8 doesn't, but its fast enough that some are working to compile other languages into JavaScript to run on V8 and take advantage of its capabilities.

    As a interpretter/runtime/vm, the development goals are a bit different than a language. With PHP, it feels as if they're one in the same. So people who try developing other interpreters are having a hard time keeping up with discussions when all of the language-design discussion is mixed in with the PHP-interpreter discussion.

    As an interpreter, I feel that the more languages the interpreter supports the better. Why can't we have a <?python or a <?javascript or a <?actionscript. I'm tired of rewriting code in another language so I may use it there. Some are already trying to do this, it'd likely rally up support from other areas of the community.

share

It seems that nobody mentioned an optional  type safety.

It would be great to be able to write code like this:

<?php
$someVariable = 123;
$someVariable = "Hello World";

int $anotherVariable = 123;
////$anotherVariable  = "Hello"; // This must cause runtime exception.
////int $lastVariable = "World"; // This must cause it too.
?>

Another example:

<?php
// Current style (which must remain).
function SayHello($howManyTimes)
{
    if (!is_int($howManyTimes))
    {
        throw new Exception('Argument $howManyTimes is invalid. An integer was expected, instead of ' . gettype($howManyTimes) . '.');
    }

    echo str_repeat('Hello', $howManyTimes);
}

// New, optional, style, allowing to have a shorter code.
function SayWorld(int $howManyTimes)
{
    echo str_repeat('World', $howManyTimes);
}

SayHello(123);
SayHello("Hello World");

SayWorld(123);
////SayWorld("Hello World"); // This must cause runtime exception.
?>
share

Being wise enough to not breaking backwards compatibilty. I've learned the existence of goto as a keyword the hard way, I was using it as an method name, so an update of my code for php 5.3 took 2 or 3 hours.

Something like roles for classes would be a good addition to the object system. Nothing complicated.

class abc { use xyz::method; use uvw::__all; }

This would pick method method from class xyz and all methods from class uvm.

Constructor call should be useable as a object right after creation.

new goodie()->youp();
share

Native regexp literals, Perl-style qw{}, qq{} and q{} quotes.

The chained method call for all objects: $object{ ->method1(); ->method2(); ->getPerson()->getName(); }

The statement expression: ({echo $a; $a = $a + 1; $a})

CONSISTENT, NON-CONFIGURABLE, CANNOT BE TURNED OFF short_open_tags. If they are not configurable, PHP code will be more portable. See wha including the ERB-style tags

share

It would be nice to be able to use a class that extends iterable in a foreach loop, where you pass a reference to the loop:

foreach(&$myclass as $me) {
  echo $me;
}

I haven't spent much time looking into why that doesn't currently work, perhaps it's related to how iterables work, I haven't investigated much more than just noticing that it doesn't work.

share
  • UTF-8 support
  • Make the language fully OO, borrowing the Ruby and Python concept that everything is an object. I kinda liked the autoboxing rfc. However it gives way too much freedom to the developers which is not that good. But with some limitations it could be a nice addition to the language evolution.

$x = array(5, 60, 50, 50); $x->map(function($i) { return $i * 2; })->push(10);

$p = "some string"; $q = $p->substring(0, 10);

etc.

In my oppinion this can be done without breaking the current global functions. However, most of them will become useless and could be deprecated over time.

  • Short notation for arrays would be nice, but it's not critical for the language.
share
  1. Consolidate the object model - make all objects extend base Object class. The Object class would (among other things) implement all the magic methods (so they'd be no longer magic!)

  2. Move extensions to their own namespaces - unclutter the global namespace $conn = new \MySQLi\Connection();

  3. Un-cripple the spl_autoload() function! Seriously, this is possibly one of the greatest features of PHP and also the most useless at the same time. spl_autoload is the default autoloader, that supports namespaces and multiple file extensions, but for some unknown reason requires the filenames to be lowercased. There is a bug report filled for this, but the staff replied they won't fix it because of backward compatibility. Right... it's not like every framework ships with it's own autoloader, since the default one is crippled!

share
  1. Immutable value objects
  2. Anonymous classes and/or classes as objects
  3. Builtin object equivalent to string data type (mentioned earlier)
  4. Annotations or Python-like decorators
  5. Singleton objects like in Scala
  6. Default errors as exceptions (mentioned earlier)
  7. UTF8 support
  8. Removal of global etc
  9. Unified access principle - one way to call object methods and manipulating properites (see Scala)
share

When I saw this thread I thought that it would be useful to mention some articles I ran into.

  1. Sort of Groovy Groovy’s ?. operator in PHP: http://justafewlines.com/2009/10/groovys-operator-in-php-sort-of/
  2. Improve closures: http://justafewlines.com/2009/10/whats-wrong-with-php-closures/
share

few things that would make my day

  • Sane naming conventions for built-in functions.
  • Type hints for strings and numerics
  • Return type hinting
  • E_STRICT on by default
  • Traits, mixins, & multiple inheritance
  • Everything is an object (i.e. ruby-like pureness)
  • Add :: support to namespaces
  • Better windows support
  • Testing out of the box
  • Better documentation for the underworkings of exec()
  • Redesign of php.net with live-search
  • Xdebug like functionality out of the box
  • Improvement of PEAR portability - users of ruby gems should know
share
  • I'd like to see some native way to set open_basedir in virtual hosts based on domain name automatically, without having to configure one directive per host (similar to Jason Greene patch, but native).

  • Please, application-wide globals! App global variables would be available to all php scripts, once initialized.

  • Some way to release session for other threads, without closing them:

session_start();
$_SESSION['favcolor'] = 'white';
session_flush(); // session is now unblocked so other threads can use it
// huge loop ...
$_SESSION['taste'] = 'sweet'; // session blocks automatically again
session_close();
  • Maybe some on-disk cache would be nice, so we can precompile php scripts manually for faster execution. Similar to memory caches, but with files on disk and manual generation (probably using some new file extension).

  • Also, something similar to <?php =$variable ?> as shortcut to <?php echo $variable; ?> would be nice (as in asp tags, but with short/asp tags disabled).

share

PHP needs an immutable Unicode string class. Ensuring input strings are valid, normalized UTF-8 and that it stays valid should be trivial.

$str = new Utf8String('āll īs ōk');
$str = $str->ucwords(); // Āll Īs Ōk
$str = $str->strtolower()->toAscii(); // all is ok
(string) $str; // UTF-8 bytes

I made a prototype based on PHP-UTF8.

share

I would like to see a legit method of creating/defining CONSTANT arrays. There are a few hackish ways to simulate this kind of functionality but it would be nice if it was just a straight up feature of PHP. It would be nice if you could create an array in a way that is similar to Java's "final" declaration.

I created a login system that is very quick to setup. All you have to do is change the contents of an array in a text file to specify the fields you want for user information. Using a swath of for loops it handles everything from form generation and input sensitization, to database calls but it is all dependent on this original array.

The file with the array is locked down with permissions but once the array is moving around in the ether it is mutable. Although I feel the system is pretty secure I don't like leaving anything to chance. A method to finalize arrays would be nice for a situation like this.

New Idea!!

Ohhh, I thought of something else I would really really like in php. I would like some kind of system to control php file operations and directory operations similar to the way .htaccess works.

The .phpaccess file should trigger some kind same domain/same origin policy.

For example, If I were hosting many sites with virtual hosts I could have a .phpaccess file in a directory that would tell php to check the orgin of any scripts being executed which are trying to operate on my protected directory. If the script did not come from that directory or its sub-directories then the file operations / or socket operations will be denied.

I think a system like this would make virtual hosting a much safer environment. If you could place one of these at the top of each virtual host it would lessen the chance of someone finding a way to sneak in from a neighboring virtual host.

Also if it would be good to have a method of securing it in the inverse of this manner. ie, restricting the reach of scripts in a single directory to that directory.

Its the yin and the yang ya know!

share
1  
there's a proposal for getters/setters for trunk that would supercede readonly, etc. Immutable arrays though probably would be hard to do. –  StasM Dec 18 '10 at 22:45

1) Shorter array/object syntax, a la JavaScript (as previously mentioned)

2) Allow const variables to allow the result of a calculation like define() does.

3) Chaining directly from the constructor: new User()->name('Ryan');

4) Array dereferencing: something_that_returns_array()[4];

5) Expanded SPL support. SPL does a decent job of reimagining string and array functions (among other things) as objects. Expanding SPL could solve a lot of gripes about the language being so janky.

6) Using ArrayObject() should be as transparent as using array(). You should be able to do things like array_filter($array_object_instance) without doing array_filter($array_object_instance->getArrayCopy()). Even better, of course, would be $array_object_instance->filter().

7) Full-on Unicode would be nice.

8) Stop doing weird automatic type conversions. For example, you should not be able to echo a SimpleXMLElement object without first explicitly typecasting it as a string. Or at least, throw something when it happens (e.g., in strict mode, or whatever mode error_reporting(-1) is).

9) Support for either multiple threads, or some sort of evented/asynchronous callbacks. This matters most when trying to upload large files via cURL. Instead of old-skool threads, something like Apple's Grand Central Dispatch would be nice. Or even something JavaScript-like where you can make async requests and define callbacks.

10) Consistent naming/order (i.e. needle haystack) would be nice, but I think this could be better solved with SPL.

11) An officially supported interactive PHP shell, like IRB. Facebook has one called phpsh that was written in Python, but it lacks the polish I would like to see.

12) For the Reflection API, add support for (a) docblock comments on constants (global & class), and (b) support for parsing PHPDoc-like comments into a sensible data structure. There's a PECL package called "docblock" that attempts to do this, but it doesn't appear that the author got very far.

EDIT: 13) I would also love to see the ability to use ! and ? in function names -- like Ruby can.

share

My first two annoyances has not to do with PHP, but with its implied usage conventions.

  1. 'The file name extension' for library code (e.g. PEAR/Horde/Zend/etc.) should end on .phps instead of .php. The benefit of this is that it clearly separates code to run and code to include, as well as that optionally all (your) code is pretty readable/browsable from the server. As a bonus, spl_filename_extensions() can be used in your autoloader for other's convenience.

  2. The convention (in the documents) is that :: is used for both static as well instance methods, I would be thankfull if they would use :: for static and -> for instance stuff. As a good convention there still will be room for error concerning interpretation, but it's at least more clear.

To name a few, I would also like to see the following:

  1. Reflection*'s getDocComment (or perhaps another variant of the name or argument) should be more liberal and also get just the first comments (until space) above the mentioned type. In other words: I don't like the verbose (read: line eating) doccomment while I really just want to be able to provide the bare minimum in any kind of commenttype: //, #, or /* ... */.

  2. List of used namespaces, e.g. getdefinednamespaces().

  3. The behaviour of 'undefined constants' should be changable by an ini directive, e.g. an empty string or fatal error. Nevertheless, it should never be implicitly transformed to a string! (it's like the ; in javascript).

  4. The constant __CLASS__ should also automatically work like this (called statically) stdClass::__CLASS__ == '\stdClass'. In other words, instead of referring to a class by a string, I want to use a class and its magic constant __CLASS__ to refer to it. (yes it is an idefix)

  5. Type casting and magic methods __fromType($instancetype) and __toType($type). So an object can be casted to an integer: $y = (int) $x or to another object $y = (BeanWrap) $x. Nevertheless, an implementation of this means that of the twelve available casts which cover eight different types, the names of these casts can not be used as classnames (e.g. int, binary, boolean) anymore.

share

I would like to see an else clause for while, for, and foreach. E.g.:

while (/*condition*/) {
   /* display each result */
}
else {
   /* condition was never true; display "no results found" message */
}

The else block is only executed if the condition for the while was never true.

This would make it so you wouldn't need to keep track of Boolean flags, and perhaps it could help you think about boundary cases and possible error conditions.

share

and, obviously, get_shutdown_functions() and unregister_shutdown_function(). Currently there is no way to acces that. And more generally, some abstract support for callback stacking - something to unify spl_autoloads, shutdown functions, error handlers (currently not stackable, but maybe...) etc. Kind of register_callback($callback, $stack) and so on , with some predefined stacks ('autoload', 'shutdown', 'error' ...) called by php or by user itself.

share

adding object wrappers for extensions using resources (curl, ftp, gd2 ... ). Like

 $oFtp = new Ftp();

 $oFtp->connect();

 $oFtp->close();
share

support for type hinting for all types, and _toXXX magic methods for every type possible. (php common usage drifts IMHO rather to limit type juggling /with some exceptions, such like convertion float<->int/)

share

Ability to throw exceptions in __destructor or __toString. And, really, is there any explanation why it is not possible?

share
1  
Yes, there is. Dtor may be called in random moment in unrelated code, so there's no reliable way to catch such exception. As for toString, the problem is probably more technical - it would lead to too many checking in various conversion routines. –  StasM Dec 25 '10 at 2:05

Generators. As in Python, with yield.

share
1  
I wonder if it's possible already, having closures and iterators... –  StasM Dec 25 '10 at 2:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.