88

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.

Macneil
  • 8,223
  • 4
  • 34
  • 68
StasM
  • 3,377
  • 2
  • 23
  • 28
  • 2
    I like constructors the old way better. – johnny Dec 17 '10 at 22:57
  • 9
    @Stan: Much as you'd like to avoid that kind of comment, you're going to get it anyway. The [problems](http://programmers.stackexchange.com/questions/696/why-do-you-hate-love-php-closed) [people](http://programmers.stackexchange.com/questions/2323/why-is-php-considerd-the-darkside-of-programing-closed) [have](http://programmers.stackexchange.com/questions/21048/is-a-php-a-good-language-to-start-with) with PHP are largely in the categories of things you're ruling out in your post. [...] – Fishtoaster Dec 19 '10 at 00: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 00: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 07: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 08:23
  • 3
    @Fishtoaster: I am aware of the fact that some people would rather rant than contribute. I don't think there's any "situation" here, and so far majority of the answers were useful and helpful, for which I am grateful. If somebody still uses this opportunity to vent - well, I hope he feels better after that :) – StasM Dec 19 '10 at 09:20
  • 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
  • 1
    @StasM: Talking the design, PHP lacks AFAIK The Specification - you know, the great one. Doc is awesome (even if it has great holes), but there is not specification. If you take look at stackoverflow, there is many questions (concerning ie. C/C++, C#, Python, Javascript, SQL) which could be responded because there exists clear specification with (nearly) all responses. – ts01 Dec 25 '10 at 01:44
  • I tend to just use features after they exist, but this seems like a really good idea. I work at a PHP-heavy shop and have shared this link with my coworkers. – nc01 Dec 25 '10 at 04:54
  • 1
    Can people try to stick to one feature per answer, and vote on other peoples that they agree with. You can post more than one answer if you want more than one feature. I'm finding it hard to agree with some points that are point 4 in one post and point 8 in another post. – rjmunro Jan 06 '11 at 23:37
  • 3
    Does "disappearing into the void, never to be seen again" count as a feature? – Jason Lewis Jun 22 '11 at 13:43
  • 2
    Number 5 removes the only correct answer! – alternative Jun 22 '11 at 16:25
  • both these comments...hahahahah, simply brilliant. I think I cracked my rib there – Shades88 Sep 14 '12 at 09:45

63 Answers63

119

I wouldn't mind named parameters.

getData(0, 10, filter => NULL, cache => true, removeDups => true);
// instead of:
getData(0, 10, NULL, true, true);

// or how about:
img(src => 'blah.jpg', alt => 'an albino platypus', title => 'Yowza!');

Unfortunately the PHP devs shot that idea down already.

  • 1
    It's the list from 2005. Many ideas were shut down and then reborn. Actually, if a good implementation comes, there's a decent chance it'd be accepted. – StasM Dec 18 '10 at 17:21
  • 21
    It's my favorite python feature. Makes the code very self-documenting. – Benbob Dec 18 '10 at 17:21
  • Aye, this would be particularly useful, save passing an options array. – Orbling Dec 18 '10 at 17:55
  • I'd rather have a better notation for arrays or anonymous objects, although I'm not sure what would that be :) I.e. getData({ 0, 10, 'filter' => NULL }). – Michał T Dec 18 '10 at 18:29
  • I'm not sure what you find issue with. This is easy to do. `make_img(array('src' => 'blah.jpg', 'alt' => 'an albino platypus', 'title' => 'Yowza!'));` – Josh K Dec 18 '10 at 20:19
  • 7
    @Josh K: It's possible alright, but the 'array' call is useless garbage if you will. It only obfuscates what you are REALLY trying to do. Another option would be a shorthand syntax for arrays: make_img(['src' => 'blah.jpg', ...]); – Erik van Brakel Dec 18 '10 at 21:52
  • 2
    @Erik: That's not a bad option either, I'm saying why add this clutter to a language when you can do it already with a minor array wrapper. – Josh K Dec 18 '10 at 22:04
  • @Erik: I agree, I don't want to confuse named parameter syntax for associative array syntax. – BoltClock Dec 18 '10 at 22:57
  • 4
    @Erik: More relaxed syntax for arrays (like JavaScript's `[]` operator) would be an appreciated feature. – Josh K Dec 25 '10 at 20:47
  • Great idea. This would be the first step to clean up the messy syntax of the functions in the global namespace. – takeshin Dec 26 '10 at 09:28
  • 1
    I would love this feature, it's one of the really nice things I liked from Python. @josh_k: Problem with doing it that way is now you have to do all the data checking yourself. Maybe a parameter is required? Maybe alt is defined as a certain type only? Now you have to check yourself, before PHP would check for you. And any IDE's that try to do nice auto-completion stuff now don't work. – James Dec 28 '10 at 12:13
  • @JoshK Because the function signature has meaning when using named arguments. PHP (or your IDE) can then reveal any error (invalid arguments) before you run the function rather when your code runs. This is a big win for preventing bugs. It's just more semantic when it's integrated into the language. Python has this and it's certainly not a cluttered language. – Benbob Jan 11 '11 at 12:08
  • @Keyo: PHP is interpreted, not compiled. While I value (and love) a strongly typed compiled language *for that very feature* I think you would find it difficult to implement in PHP. I'm picking up more Django work now and I agree, named parameters are nice. I would settle for a more relaxed syntax though. – Josh K Jan 11 '11 at 14:00
  • The reasoning on that page is gold: *"We don't see the real need for named parameters, as they seem to violate PHP's KISS principle."* haha, what? :D – Tamás Szelei Jun 22 '11 at 13:49
93

More dereferencing:

echo something_that_returns_array()[4];

Others have mentioned named parameters, and shorter array syntax. I wouldn't mind shorter object syntax, as well.

$a1 = array(1, 2, 3, 4);
$a2 = [1, 2, 3, 4];

$b1 = (object)array('name' => 'foo');
$b2 = {'name' => 'foo'}; // or something?
Annika Backstrom
  • 707
  • 4
  • 13
  • 18
    ()[] syntax is already in trunk. Unfortunately, array shortcuts were rejected, but I hope for resurrection. – StasM Dec 18 '10 at 22:44
  • 2
    I would love this feature. Why can we have something_that_returns_object()->4, but not with arrays? – Bala Clark Dec 19 '10 at 08:22
  • @Adam: _[shameless evangelism]_ You should check out Ruby. Has everything you mention, plus no sigils and ending semicolon. – Mladen Jablanović Dec 19 '10 at 08:49
  • 4
    Javascript like array and object notations would rock. As a front end developer that is what bothers me most in php code. – Bleep Bloop Dec 23 '10 at 00:27
  • The problem with the example `()[]` syntax is that it only works if the function *always* returns an array with at least 5 elements in it. – DisgruntledGoat May 20 '11 at 18:41
  • 1
    @DisgruntledGoat It does, see: `function something_that_returns_array() { return array( 'a', 'b', 'c', 'd', 'e' ); }` – Annika Backstrom May 21 '11 at 01:55
  • 2
    @DisgruntledGoat: The problem with the `()->` syntax is, that it only works when an object is returned, to make matters worse, the object is even required have a property/method of the specified name, which, optimally, does what you hope it does, while accepting the parameters you've given it, and praying that it doesn't require any more... etc etc. – phant0m Jul 23 '11 at 23:44
  • Just in case anybody reads this: [1, 2, 3, 4] is in PHP 5.4 too. – StasM Apr 13 '12 at 19:41
72

After working with PHP for about 13 years, and heavily with JS for about 4, there are a couple things I think PHP would do well to borrow from JS:

1) shorthand notation for Arrays and Objects. I believe this may have been discussed and shot down on Internals (so I hear – I don't like to see how the sausage is made), but I really, really find that the literal notation for arrays and objects in JS is a big productivity win.

For example:

$arr     = [1,2,3,4];
$assoc   = [foo=>'bar', baz=>'boo'];
$stdobj  = {foo->'bar', baz->'boo'};

Is (IMHO) just much easier to write and cleaner than

$arr     = array(1,2,3,4); // not too bad
$assoc   = array("foo"=>'bar', baz=>'boo'); // not too bad either
$stdobj  = new stdClass; // this gets pretty rough
$stdobj->foo = 'bar';
$stdobj->baz = 'boo';

I've heard that some concern about potential confusion was raised, but really, is this any more confusing than, say, heredoc notation? At very least, making a stdClass object in PHP is verbose enough to discourage the practice, I think.

2) Being able to redefine previously-defined functions and methods would be really useful. It would particular simplify situations extending a class and instantiating the new class is either overly complex or impractical. I do think we should avoid redefinition of core/non-userspace functions and methods, though.


In addition to those two, I think PHP must transparently support unicode. This is becoming more and more of a problem for developers, and the solutions currently offered in PHP are confusing and frequently non-performant. Making all standard string functionality unicode-friendly out of the box would be a massive win for PHP programmers.

Thanks for asking!

Funkatron
  • 191
  • 1
  • 4
  • (2) look at runkit. (3) unicode is hard, especially since most of outside world is not unicode. We'd have to either kill performance or require people to do a lot of extra work (like Java does). That's why php6 unicode effort didn't work out. – StasM Dec 18 '10 at 23:06
  • I'm aware of Runkit, but it's just not a commonly supported extension, so you can't rely on it to be in the environment. Making some of its capabilities available in the core distro would allow then to be used of by a much wider audience, and allow public/FOSS projects to take advantage. – Funkatron Dec 18 '10 at 23:19
  • 8
    As for unicode: it may be hard, but it would be massively useful (surely developing PHP itself is hard, but it provides great benefits, yes?) Perhaps a solution would be to enable transparent unicode via an extension with the understood perf tradeoff, much like XHP? Thanks again. – Funkatron Dec 18 '10 at 23:21
  • 5
    $object = (object)array("foo"=>'bar', baz=>'boo'); – mercutio Dec 19 '10 at 09:55
  • 3
    I don't see how you can see "most of the outside world is not unicode"? Are you talking about people? Or something else? Because the vast majority of people in the world (by a **huge** margin) speak languages that are best represented by Unicode. – Dean Harding Dec 19 '10 at 22:15
  • 1
    Definitely unicode support. Shipping any sort of globally used app is a non-starter without it. Whether the PHP devs think engineering in decent unicode support is easy or not is beside the point. People need it, and they're hacking their way around the platform's failings to do it. Delphi did it by adding another string type and making it the default, with implicit casting, and a global switch to get the old behavior back. Why can't PHP do it the same way? – Joeri Sebrechts Dec 27 '10 at 19:40
  • No 2. Oh please no. "I do think we should avoid redefinition of core/non-userspace functions and methods, though." Is that because code could become very hard to understand? (I thought it would do this, I didn't realise someone else had redefined the function!) Well, the same applies to my code & functions. This could make code so hard to follow. But Yes on the unicode. – James Dec 28 '10 at 12:18
  • Yes, being able to just put in a json and have it work would be very helpful. – Zachary K Feb 18 '11 at 13:24
  • I don't care about redefining functions, but I'd like short-hand syntax and *definitely* unicode – Xananax Jun 22 '11 at 05:20
48

Things I would like, as a former long-time PHP apologist:

  1. Shorter syntax for arrays. PHP arrays are one of the awesomest features of the language because of their flexibility, but it's a drag to write some_array_method($argity, array('key' => $value));. I believe this proposal was already eviscerated on the PHP mailing list unfortunately.
  2. finally support
  3. Attributes/annotations. These allow you to add custom behavior to a method in a way that allows code reuse. For example, in an MVC framework, one could define an AuthorizeAttribute that would indicate that a controller or action method requires the user to be authorized. The framework itself would be responsible for looking for the attributes and acting on them accordingly. I believe PHPUnit already uses a sort of attribute by putting them in docblock comments, which can be read using reflection, but putting actual functionality in docblock comments is certainly a hack.
  4. Shorter lambda syntax. Instead of having to write function($x){ return $x*2;}, maybe I could write $x => return $x*2, or something. This is again something just sort of makes it a drag to use this feature. For example $results = array_filter(array(1,2,3), function($a) { return $a % 2; }): vs $results = array_filter(array(1,2,3), $a => return $a % 2 ); The former just has so much more plumbing that's basically irrelevant to the actual work you're trying to accomplish.
  5. A built-in Decimal (fixed-point math) that supported math operations through the normal operators would be kind of nice, since we don't have operator overloading.
  6. MOAR MAGIC METHODS. Magic methods are great. I could see PHP adding operator overloading via magic methods (I know this will basically never happen.) But in general, they provide really great ways to hook into the language and do cool things.
davidtbernal
  • 388
  • 3
  • 11
48

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?

Nicholas Shanks
  • 337
  • 2
  • 12
Benbob
  • 1,216
  • 9
  • 22
  • 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. – Benbob Dec 18 '10 at 17:28
  • Funny thing — if all scalar types were objects, we would get strict typing in function calls for free since `function blah(MyObject $foo);` will already work, and if a String class existed, then it would be no different to function handling than MyObject. – Alan Pearce Dec 20 '10 at 11:29
  • Somebody has never understood Scheme. – erjiang Dec 21 '10 at 00:52
  • 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 06 '11 at 23:39
  • @rjmunro The best way to fix PHP is to use python or ruby. Clearly they don't take any of the criticisms on board. – Benbob Jan 07 '11 at 01:08
  • @rjmunro Or have an "encoding" parameter, with UTF-8 default. – luiscubal Jan 18 '11 at 01:45
  • 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 00:00
  • +1 from me, my thoughts exactly. If PHP went fully OO, it could actually be adopted by .NET developers rather than flamed by them. – Greg Jun 22 '11 at 09:41
  • @rjmunro Or PHP could implement named parameters and it would be easy to add a named encoding parameter :-) – Andrea Jun 24 '11 at 09:30
40

A language-integrated-query-engine would be great. Sort of like what is available in .NET called LINQ. It would help sort through massive arrays of data, and standardize database access, so that fewer SQL-injection attacks succeed.

Stephen
  • 2,200
  • 6
  • 22
  • 24
Nick Berardi
  • 799
  • 5
  • 8
  • 2
    Anything that makes parameterized queries easier gets my vote! – Dean Harding Dec 18 '10 at 14:57
  • 1
    I think the standardized database access is actually a very important benefit of something like LINQ, because I think it makes unit testing with mocks of your database objects easier (since you're mocking PHP code instead of SQL queries.) – davidtbernal Dec 18 '10 at 19:42
  • i don't think, that something like this should get into core. it would better fit into a pecl extension – aurora Jun 03 '11 at 07:21
38

Oh. Type hinting for primitives. That would be nice.

  • 1
    Although I like PHP's KISS principle (to an extend), I strongly second that. The reason is that if you want to be really defensive, you end up with the same type checking code in *each* setter method. We could easily drop that if the language supported it natively. – MicE Dec 18 '10 at 22:26
  • 4
    "Type hinting" was very unfortunate name, as it's not "hinting", it's strict typing. I think primitive strict typing would be out of place in dynamic language like PHP. Coercive typing (same thing that internal functions do - try strlen(123)) may be OK. – StasM Dec 18 '10 at 22:42
  • 6
    +1 for this. Type hinting (or strict typing) in function declarations would be incredibly helpful and cut down on so much if(!is_int()) crap in EACH AND EVERY method. – Phil Sturgeon Dec 21 '10 at 11:54
  • 5
    @StasM I disagree. It is perfectly with in the scope of a dynamic language to allow the user to choose to use the language in a statically typed way. And it would allow for much better error catching. You wouldn't have to use it if you didn't want to, but personally I'm fed up of having strings passed where I wanted an int and then having to search through code to figure out where the stupid string is getting passed in. Or else, type checking everything all the time. – Daniel Bingham Dec 28 '10 at 17:15
  • @Daniel IMO "better error catching" is a myth. Since without compiling you don't have static type control, the errors in runtime will stay the errors in runtime, you will just shift them around the code. On the other side, you'll add tons of type conversion errors - like "1" and 1 and 1.0 being different, and you'd have to either introduce typed variables, returns, etc. - thus converting PHP into fully statically typed language - or do three times as many checks, as you move the check form the callee to the caller. – StasM Dec 28 '10 at 19:01
  • @Daniel note also that none of the PHP's peers - Python, Perl, Ruby - have statically typed methods. Is there a reason for that? – StasM Dec 28 '10 at 19:12
  • 2
    @StasM There is absolutely no reason you would have to introduce fully statically typed variables. Yes, you would shift the errors around in your code. That would be the whole point. The error would occur at function call time instead of inside the function -- which leaves you with no idea where the error is actually occuring. As for type conversion errors, the error would occur -- yes at run time -- at the function call. Fix the problem by converting right there to the correct type. Much better than having a string appear in a function expecting an int and not knowing from where. – Daniel Bingham Dec 28 '10 at 21:33
  • 1
    @StasM And before classes were introduced, there was no other language that had them either. Was there a reason for *that*? This sort of argument is the worst of red herrings when it comes to language design. The whole point of innovation is that it doesn't exist yet. – Daniel Bingham Dec 28 '10 at 21:33
34

I really wish for better unicode support out of the box. Most languages move in that direction but PHP still have strange commands littered all over.

PHP strings are just plain byte arrays. Their content is non-portable as it is dependent on the current default encoding.

The same applies to the representation built by serialize. It contains a length-prefixed byte representation of the string without actually storing any encoding information.

Most PHP (string) functions have no clue about Unicode. For a detailed list including each function’s risk level, refer to: http://www.phpwact.org/php/i18n/utf-8

http://blog.ginkel.com/2010/03/php-unicode-support-or-the-lack-thereof/

Emil Stenström
  • 151
  • 1
  • 3
  • Unicode support proved much harder than thought. That's why php6 effort was stalled. For now, we have utf-8 and I think best way to go would be to add utf-8 support for string functions, maybe as part of intl extension. – StasM Dec 18 '10 at 22:38
  • 3
    BTW, the quote is incorrect. PHP strings are byte arrays, but their content is as portable as you make them and is not dependent on "default encoding" - it's just array of bytes, you want them in utf8, put utf8, want utf16 - put utf16. phpwact.org link seems to be dead. – StasM Dec 18 '10 at 23:31
  • 1
    I would really hope that the intl extension would be enabled by default, so people that needed UTF-8 (doesn't everyone?) didn't have to fight their hosts to get the string functions to behave like expected. – Emil Stenström Dec 19 '10 at 12:19
  • Also, thanks for the clarification on strings. I've been away from PHP for a while now, so I'm a bit rusty. I've instead fought the unicode war with Python, which has similar problems as PHP does, but solves them in Python 3. Having a swedish "ö" in your name is a mess :) – Emil Stenström Dec 19 '10 at 12:20
  • This is definitely one area I would like to see an improvement in. – Nathan Osman Dec 27 '10 at 00:27
  • This has been discussed and attempted before, but turned out to be quite cumbersome so the team stopped branch development. It required a full re-write of almost all aspects of core. – Corey Ballou Jun 10 '11 at 11:57
  • I think that PHP should assume all strings are UTF-8, and any function that expects a string (not binary) should throw an exception if the UTF-8 doesn't validate. – rjmunro Jul 03 '13 at 13:38
32

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.

rjmunro
  • 416
  • 4
  • 10
  • up, that's exactly what I'm aiming to. – Kemo Dec 18 '10 at 22:44
  • 1
    `subject->verb(object)`, makes parameter order easier to remember. – Ming-Tang Dec 30 '10 at 04:09
  • +1 I played around with creating my own string class to do this kind of thing, it makes coding so much easier and you never forget the parameter ordering. – DisgruntledGoat Jan 06 '11 at 17:22
  • 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
  • @Tgr: is_object() should be deprecated - There should be no such thing as "not an object". In the short term, it would have to be a property you can turn off on any object, and the default string constructors would turn it off. – rjmunro Apr 16 '11 at 23:50
24

1) I would love for newly instantiated objects to return "$this" so I can method chain, $user = new User('john')->setLastName('Doe')->save();

2) If you've ever used ruby, and most recently node, they have a great interactive shell (IRB). I would love for PHP to have one that was actually useful.

3) Traits/Mixins, but I hear those are on the way.

4) I want to second the short array $myArray = ['my', 'array'];

5) Consistent naming/order (i.e. needle haystack)

  • I hate having to create a `create()` method that does nothing special just to work around #1! – Alan Pearce Dec 20 '10 at 11:30
  • I do the same but, using late static binding and an object superclass, that way every class that extends my superclass has the method, e.g.: SomceClass extends SuperObject{}; SomeClass::create()->somemethod(); – dukeofgaming Dec 21 '10 at 02:23
  • Have a look at https://github.com/philsturgeon/php-ps It's only a start but with some help it could be pretty useful. – Phil Sturgeon Dec 21 '10 at 11:52
  • 1
    There's also a PEAR package that offers an interactive shell for coding out quick experiments in PHP - available at http://pear.php.net/package/PHP_Shell – kguest Dec 25 '10 at 22:55
  • (new Foo())->bar() is part of 5.4. 3) and 4) are too. – StasM Apr 13 '12 at 19:44
20

1) please get rid of includes(). References to other files should be references, and not actually place the contents of one source code file into another. Far too many PHP programmers use includes() as a type of function call rather than a means to reference a library. This leads to all sorts of ambiguity in variable state and unstable code. Replace this with a Perl-like 'use' command.

2) please provide an out of the box method of compiling a PHP application into a single distributable bytecode file or executable. This will greatly enhance the appeal of PHP as a commercial development language. This should be a basic component of the language. Dont worry about the html files used for an application's GUI because...

3) please get rid of the ability to embed PHP tags into HTML. Or at least provide a 'no embed' mode. This is an absolute mess and encourages bad design by mixing application logic and presentation together. Developers should be using templates for display and not slapping PHP files together and hoping for the best.

Signed,

GrandmasterB

ps: dont listen to what others here say, I've been nice all year

GrandmasterB
  • 37,990
  • 7
  • 78
  • 131
  • 2 is kind of hard. Look at hiphop (https://github.com/facebook/hiphop-php) though - it shows some promise. – StasM Dec 17 '10 at 21:58
  • 37
    1). Includes are great. Everything has includes. 2). This is good. 3) Templating is PHP's **strongest feature**. Forcing you to use some other templating bullshit would be a very bad move. – Josh K Dec 17 '10 at 22:46
  • @Josh K: I agree, why bother moving to another form of templating? I think HTML-based code should be limited to loop-constructors, and quick echoes, using the ternary-if rather than any code where necessary. If people choose to use more complex code inline, that is there own lookout. Otherwise you end up with design elements in the code, which is much worse. – Orbling Dec 18 '10 at 14:09
  • 8
    I like (1) and (2), but (3) seems like a retrograde step. PHP gives you the templating power, it's up to you whether you use it wisely or not. – geekbrit Dec 18 '10 at 19:23
  • 11
    3 makes no sense - embedding tags is necessary for any V in MVC frameworks. – Alex Dec 18 '10 at 23:05
  • Bundling a whole application is not as easy as you think and I think in many cases would be impossible to do automatically without sweeping changes to how PHP works. – Michał T Dec 20 '10 at 15:09
  • 9
    I read this answer as "Dear Santa, please make PHP not be PHP." – Stephen Dec 21 '10 at 22:50
  • (2) are you asking for something more than phar or an extension to phar? http://php.net/manual/en/book.phar.php – Wil Moore III Jan 03 '11 at 07:40
  • 1
    3 is right out, as PHP _is_ a templating language. – Andrew Jan 28 '11 at 14:50
  • 1
    Umm, for naysayer's on 3... I agree that it necessary for the language, however - It would be nice if I could have pure php script files. Such as when I'm writing a class file or something, I don't want to risk sending content before the headers are sent. – tylermac Jun 24 '11 at 19:19
18

An ini directive to E_ERROR on undefined constants, rather than assume it's a string with E_NOTICE.

Annika Backstrom
  • 707
  • 4
  • 13
14

Normalize the global namespace with a well thought-out naming convention that makes sense to new-comers!

To quote our beloved Jeff Atwood: PHP sucks but it doesn't matter!

  • 1
    I agree in principle, but have no idea how to do it in practice :) – StasM Dec 18 '10 at 22:47
  • 3
    @StasM: I imagine the first step would be to make the new versions of libraries namespaced and allow programmers (via ini settings) to disable the currently global libraries. I would think a compatibility pack would be in order for older versions, but shouldn't be very difficult to write. – Michał T Dec 20 '10 at 15:15
13

Strings should be objects

Kemo
  • 111
  • 4
13

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.

Ryan Parman
  • 101
  • 4
  • i agree, that arrayobject should be supported for the array_* functions. but what would be the expected result for something like "array_merge" if you consider subclasses of arrayobject. would you only be allowed to merge instances of the same class and what would array_merge return? a php array or an instance of arrayobject (respectively it's subclass)? – aurora Jun 03 '11 at 07:24
  • I would argue that since the data internally is an array, and ArrayObject wraps that with functionality, then even subclasses of ArrayObject would still be working with arrays internally. I would expect to be able to merge another standard array or ArrayObject (or subclass). As far as what it would return, I would argue that it should also return a new ArrayObject, but follow the precedent that simplexml_load_string() set where you can specify the name of the class that the result should be an instance of. – Ryan Parman Jun 10 '11 at 21:27
12

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!

Dave B.
  • 81
  • 5
  • +1 for `final`. To clarify: `final` means that the value of a variable can be set at runtime (unlike constants, which have to be constant expressions), but can only be set once. See also C#'s `readonly`. – davidtbernal Dec 18 '10 at 19:45
  • 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
  • Re phpaccess, PHP already has a "safe mode" that does what you describe. – DisgruntledGoat Jan 06 '11 at 17:24
12

1) Array comprehension in the style of Python list comprehension:

$newlist = array($x->something for $x in $oldlist);

//with short array syntax:
$newlist = [$x->something for $x in $oldlist];

2) Short array syntax

$newlist = [1,2,3,4,...];

3) Make empty() not consider the string '0' as true

sfrench
  • 131
  • 4
  • 2
    I think for (1) something cooked from iterator & closure would be better. – StasM Dec 18 '10 at 23:02
  • +1 IMHO, this should be included in all languages, as well as iterators. They're just way to useful not to have. – Evan Plaice Jan 12 '11 at 15:30
  • `empty()` is the logical opposite of `if ($x)`, so it makes sense that `empty('0')` is true, because `if ('0')` is false. The only difference is, `empty()` doesn't throw a notice if the variable isn't set. – Andrew Jan 28 '11 at 14:55
11

My two biggest wishes as a hardcore PHP programmer:

  1. Support finally. It's a big mess to fictionally get around this through flags or similar means.
  2. I would LOVE to see support on C#'s syntax for getters and setters. When you have lots of getters and setters a simple syntax such as C#'s is a great performance booster instead of doing it the Java way and writing getter and setter methods. Magic methods are awesome in cases where you want to create members dynamically (for instance, if you want to give a template renderer some variables to use), but are no good for normal properties on which you would like the IDE to autocomplete, know their types, and so on. this would help make code smaller and still as readable and easy to use.
Johnco
  • 121
  • 4
  • 1
    1. unfortunately, it's hard to do, but definitely a good todo item 2. http://wiki.php.net/rfc/propertygetsetsyntax – StasM Dec 18 '10 at 22:59
  • @StasM: how about doing it via anotations? Something along the lines of: /** @get getFoo; @set setFoo; */ private $foo; – Michał T Dec 20 '10 at 16:16
9

Language syntax: There are some good clues in pihipi and phpreboot of what developers are interested in (though phpreboot goes too far becoming JS).

Development methodology: It would greatly enhance the lifespan of PHP.net if such surveys were actually taken into account. Do not make any more willy-nilly afternoon IRC session syntax decisions.

Individual features: Some have been mentioned before, but I'll happily burn some karma to be extra blunt here:

  • Unicode string type.
  • Bigint (see Python).
  • Runkit builtin to remove/rename/override builtin functions and classes, which aren't always that well designed.
  • Modern OOP
    • multiple inheritance (instead of complexity to support seldom edge cases with clumsy traits syntax)
    • scalars can double as objects (see Python), e.g. array() works as ArrayObject, or strings as SplString (needs usable methods, all string funcs should be available as str::toupper())
  • Deprecate the shitty shit \ namespace syntax, fix the parser, and adopt :: as alternative. You know, like a real language.
  • Any variation of LINQ (allthough I don't trust you guys do devise a sensible syntax)
  • or XML literals.
  • Get rid of php.ini runtime behaviour and semantic switches. It takes out some of the excitement, true, but would benefit developers and user base.
  • Yes, magic_quotes are not gone yet.
  • Convert Zend Engine bytecode to PBC

Albeit, if this isn't obvious, I'd happily fund anyone else to do the latter, and kill off php.net as main implementation. :P
Oh, just noticed, it's community wiki. So there's a chance you're not actually here for the karma, but genuine interest. If so, look into the <b> issue </b> which seriously hurts the language (directoritis).

mario
  • 2,263
  • 16
  • 18
  • 5
    I hate \ namespace syntax, but it's a long and sad story why it became so and it probably not going to change... Probably if I could change just one thing in PHP that would be my primary candidate. But it is what it is. – StasM Dec 19 '10 at 09:46
  • @StasM: Thanks for the feedback and sorry for being rude about some PHP things, but I do care about PHP; hence very opinionated. - I've read a bit about the reasoning. The backslash dilemma is not yet a very big issue, but it'll become next year when the libraries spread. So I hope someone writes a parser that rewrites \cargo\cult\class\names back to underscore schemes. – mario Dec 19 '10 at 10:00
  • Maybe I'm daft, but what's the difference whether we use '::' or '\' for namespaces? – Michał T Dec 20 '10 at 16:29
  • @Pies: The `::` would have been more natural for any C/C++ syntax close language. And `\\` is not only abnormal among *all* programming languages, but has untested connotations. Some previous discussions: http://stackoverflow.com/questions/238550/what-do-you-think-of-phps-new-namespace-separator or http://developers.slashdot.org/article.pl?sid=08/10/26/1610259 and http://www.reddit.com/r/programming/comments/79cut/php_is_going_to_use_backslash_as_a_namespace/ - But in particular deciding on that without feedback and signaling the developer community to suck it up wasn't a very welcome move. – mario Dec 20 '10 at 16:39
  • 1
    + 1000000 for multiple inheritance. – ts01 Dec 25 '10 at 01:25
8

I'd love to see unification of Errors and Exceptions into a single concept (Exceptions). Its great to be able to catch exceptions and write them to a log, to find and fix bugs that way. But if there's something fundamentally wrong (read: PHP Error) in a codepath that is very rarely hit, there's no good way to funnel that info into that same database of issues.

Please, Santa, introduce a switch in php.ini that would make all errors into exceptions - ideally, exceptions I can catch in my code.

Alex
  • 111
  • 2
  • 1
    There's already support in the engine for that and many extensions use it. You can also easily do it with set_error_handler() and ErrorException. Beware of E_STRICT/E_NOTICE/E_DEPRECATED though... – StasM Dec 18 '10 at 22:56
  • I'm well aware of these methods and they're really hacky. I'd love a unified way - the one that includes E_STRICT/E_NOTICE and such. – Alex Dec 22 '10 at 20:47
7

PHP suits me just fine as it is for knocking up small to medium websites; I must be a bit unimaginative, the only thing I could think of as a response to this question would be something that makes it scale better for high traffic sites.

I'm thinking in terms of spawning off processes to other cores, for example updating a database in one process while creating the output page in another process. A quick google search indicates that this can be simulated, but is not supported directly in php at present.

geekbrit
  • 409
  • 3
  • 6
  • 1
    Actually, thinking more about it, offloading database seems to be interesting scenario, so +1 on that :) – StasM Dec 17 '10 at 21:40
  • 1
    @Stasm, I assume you mean that separate requests run as separate processes. I'm talking about a complex page that requires page generation and background computation. I could be wrong, but I don't think there is a way to spawn off (for example) database update operations in a separate process. The reason for doing this would be to get the page sent to the requester sooner, rather than having to wait for all the processing that isn't directly related to producing the page to complete serially. PS.. Thanks for the update! – geekbrit Dec 17 '10 at 21:41
7

I really missed that scalar types are not treated as objects, and real objects can not act like any other type or object (except for string due to __toString()).

pestaa
  • 227
  • 1
  • 3
7
  • support for enumerations (like java 1.5+)
  • Be able to define method return types, in interfaces and classes
  • support for annotations / metadata definition on properties and methods.
  • be able to do strict type hinting for method scalar arguments.
6

Clean up "User Contributed Notes" on http://php.net. They are a real mess sometimes, while being a great value in general.

Jeremy
  • 101
  • 3
bobah
  • 728
  • 4
  • 9
  • 1
    Some sort of vote up/down functionality and the ability to link to the original comment in the reply would certainly be nice. – Tgr Apr 16 '11 at 16:54
5

There are some fairly decent array functions in PHP, providing list processing capacity, with callbacks and create_function() providing a basic lambda calculus.

The main problem with it, is that it is far too verbose in PHP, a shorthand system would be excellent, particularly where the map/reduce commands are concerned.

More importantly, the list functions are not entirely complete:

  • there is no foldr function, array_reduce() provides foldl
  • array_map() should pass the key in the second argument, as array_walk() does
  • an array_map_keys() could be useful for key modification
  • list comprehension is very clunky, range(), array_fill() and array_fill_keys() only handle so many cases, and array_filter() is separate

I'm not aiming to make PHP in to Haskell, but PHP is often used for list type data structure manipulation and having a full set of tools in this regard would be useful.

Orbling
  • 5,696
  • 1
  • 32
  • 38
  • 1
    A colleague of mine also thinks there could/should be some other additions re array related functions; at mentioned on his github account: These are are the lack of array_all() and array_any(), which check if * a condition represented by a callback holds for all or any of the elements in an array. https://gist.github.com/44350 – kguest Dec 25 '10 at 23:14
5

Operator overloading:

$result = $MatrixA + $MatrixB * $MatrixC;
MicE
  • 206
  • 3
  • 4
4

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.

rjmunro
  • 416
  • 4
  • 10
4

Add Exceptions instead of producing E_WARNING... It's very annoying that I can't use something such as:

try{
   $f = fopen('asd', 'r');
   flock($f, LOCK_SH);

   while(!feof($f)){
       echo fread($f, 512);
   }

   fclose($f);

}catch(IOException $ex){
   echo 'Oops, something wrong: '.$ex->getCode();
}

Of course, currently is not much practical but it's very annoying to receive:

WARNING

WARNING

WARNING

and I can't control the flow of code without writing my own error_handler and string sniffing which error has been produced (permission, incorrect filename or anything else; I don't mind about other sources of errors here) in order to throw correct exception.

I hope I haven't to explain why it's important.

PHP became Object-Oriented an amount time ago and we, programmers who use PHP, are looking forward for OO features, not introducing "goto"... When I found out it really happend, I thought it was an April Fool's day.

eRIZ
  • 101
  • 2
  • Unless caught, the exception will kill the script. The warning, on a production server, will get logged and never displayed to the user. Changing this functionality now would break a lot of scripts because they aren't designed to catch it. (Note, that I write error handlers to throw exceptions myself). Now, things PDO can throw warnings or exceptions: the programmer decides at runtime. That functionality is probably one that should be added to more of the modules. – Reece45 Jan 01 '11 at 00:15
4
  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!

Mchl
  • 4,103
  • 1
  • 22
  • 23
4

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).

3
  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.
rjmunro
  • 416
  • 4
  • 10
cdnicoll
  • 479
  • 3
  • 6
3

Annotations for PHP would be great, One feature that would stand out for upcoming years. This feature will help to write big frameworks with clean code.

  • 1
    The problem is to figure out what "annotations" means for PHP. I definitely don't like Java ones, they are (as most things in Java) hugely complex and serious overkill for 90% of tasks. We have some other languages too so maybe we'll find suitable model. – StasM Dec 19 '10 at 08:01
3

Don't get rid of short open tags, specially the echo one =(. This:

<?=$myvar?>

...is way better than this:

<?php echo $myvar;?>
dukeofgaming
  • 13,943
  • 6
  • 50
  • 77
  • 2
    Actually, most of the time it should be `= htmlspecialchars($myvar); ?>`. It's a shame that PHP doesn't have shorter syntax for safe HTML output. – Kornel Dec 27 '10 at 00:18
  • Are they getting rid of that? I thought it's just a configurable option and always will be...? – Dan Rosenstark Dec 29 '10 at 09:16
  • They are now off by default. Check this thread out: http://stackoverflow.com/questions/2413661/php6-is-short-open-tag-removed-or-deprecated-or-neither. The thing is that they might get deprecated, and then possibly removed. – dukeofgaming Dec 29 '10 at 09:20
  • 1
    And you don't get the point. Try reading a template/vew file with a hundred of these vs. a hundred of . I can macro it, typing it is not the point, reading it is. – dukeofgaming Dec 31 '10 at 01:02
  • 1
    Even `` would be a step up from the long syntax and shouldn't interfere with XML. Or perhaps a Smarty-like syntax `{$myvar}` . – DisgruntledGoat Jan 06 '11 at 17:36
3

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.

Macneil
  • 8,223
  • 4
  • 34
  • 68
  • Can't you just do this? `if (!condition) { /* no results found */ } else while (condition) { /* do whatever */ }` – DisgruntledGoat Jan 06 '11 at 17:38
  • @DisgruntledGoat: Then you repeat the condition code (which, in addition to creating software maintenance troubles could be executing a tricky call more times that necessary). – Macneil Jan 08 '11 at 01:03
  • true, but then the condition should be as simple as possible. Even if you're calling a function, it can usually be determined ahead of time if it will run once or not, e.g. looping through SQL results - you can check the number of rows first. – DisgruntledGoat Jan 09 '11 at 14:58
  • @DisgruntledGoat: In that case it would be better to use the flag solution instead, which at least has no repetition of code. – Macneil Jan 09 '11 at 17:16
2

Definitely method overloading using type hinting to differentiate the method signatures. Even further, I would like to see some kind of ASP.NET style "attributes", so that my controller actions in a PHP MVC framework could look like this:

/* [HttpGet] */
public function login() {}

/* [HttpPost] */
public function login() {}
Josh K
  • 23,019
  • 10
  • 65
  • 100
TaylorOtwell
  • 2,657
  • 1
  • 21
  • 26
  • 1
    if you do $foo->login(), how do you know which one of those gets called? – StasM Dec 17 '10 at 21:46
  • 4
    You could always just call them `login_get` and `login_post`. A framework can then key off of those names instead of the proposed attribute. – Justin Ethier Dec 17 '10 at 21:56
  • 2
    Actually, that code would not be valid in C#. Instead, you'd have something like `[HttpGet] public void login()` and then `[HttpPost] public void login(string name, string password)`. The attributes don't change the fundamental rules of the language. – davidtbernal Dec 18 '10 at 15:50
  • To further elaborate, `HttpPost` means the method is only available for a post request. Even if someone makes a get request with matching arguments, they would receive a 404. If someone makes a post request with no arguments (referring to my example), they would also receive a 404. This functionality is implemented at the web framework level, not the language level. The only role the language has in this is supporting attributes. – davidtbernal Dec 18 '10 at 16:14
2

Allow to namespace a file from the include call, something like this

include('mytemplate.php', 'MyNamespace');

or

include 'mytemplate.php' use MyNamespace;

And start allowing us to import ("use") namespaces without prefix:

use OtherNamespace as self;

(instead of having to import each individual class in order to use it without a namespace prefix)

2
  • Non blocking SQL Queries (Like insert some log, but don't wait for result of query)
  • Parallel SQL Queries

just a dream

  • 2
    This can be solved by DB features like MySQL's `insert delayed`. What you're really looking for is asynchronous statements. – Jé Queue Dec 21 '10 at 14:50
  • ext\MySQLi already supports this, although it's poorly documented. I did test it (in a very narrow scope) however, and it works :) – Mchl Dec 28 '10 at 16:45
2

That would be nice to have the possibility to set the primitive type (bool|boolean, int|integer, float, double, string, object) of a parameter in a method as array is allowed.

Example:

  • current:

    class HttpResponse {
    public function __construct($version, $statuscode = HttpStatus::OK, HttpResponseHeaders $headers = array(), $body = '');
    

    }

  • hope:

    class HttpResponse { public function __construct($version, integer $statuscode = HttpStatus::OK, HttpResponseHeaders $headers = array(), string $body = ''); }
    

I thought also to have an Assert static class that can be useful.

2

Generators. As in Python, with yield.

ts01
  • 1,171
  • 10
  • 17
  • 1
    I wonder if it's possible already, having closures and iterators... – StasM Dec 25 '10 at 02:03
  • it depends of some internal secrets. For example, if foreach does operate on Iterator directly or (like in case of array) on its copy. After all, there is no difference between Generator and iterator, apart of syntax which permits to use yield anywhere => you can use ordinary function as a generator – ts01 Dec 25 '10 at 04:41
  • how about this: http://php100.wordpress.com/2010/01/27/ruby-iterators-in-php/ – StasM Dec 25 '10 at 09:36
  • Cool, and kinda slow - you are creating a new instance of RubyIterator for every item. It's indeed a very good reason to have constructs like that built-in into the core – ts01 Dec 25 '10 at 09:53
  • no, it doesn't create new RubyIterator for every item in the loop, look closely. The iterator is created once when each is called. It still probably will be slower (since it's in PHP and not in C like core constructs) but not that much... – StasM Jan 18 '11 at 07:48
2

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

ts01
  • 1,171
  • 10
  • 17
  • 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 02:05
  • For destructor, if exception is not catched (ie raised after die() or when object is destroyed by gc) it could simply make "Uncaught Exception" error. But even if I can (hardly) understand such a limitation for destructor, not having this possibility for __toString suggests rather serious design flaws in ZE. – ts01 Dec 25 '10 at 04:02
  • That's what should happen for dtors now, see http://bugs.php.net/47143. toString is http://bugs.php.net/bug.php?id=53648, still open. We'll get to it one day :) – StasM Jan 18 '11 at 07:51
2

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/)

ts01
  • 1,171
  • 10
  • 17
2

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.

Steve Clay
  • 153
  • 7
2

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.
?>
Arseni Mourzenko
  • 134,780
  • 31
  • 343
  • 513
1
  • lexical scope for lambdas (using another keyword then function) (or block syntax to create an proper lexical scope?)
  • make lambdas in object properties callable
  • always imply semicolon with lambda closing braces
  • fucking add use() for normal functions!!
  • traits
  • ability to intercept instanceof / is_a()
  • generators
  • open up Exception for runtime modification
  • a function to check against interfaces without implementing it
alan blaire
  • 346
  • 1
  • 2
1

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.

ts01
  • 1,171
  • 10
  • 17
1

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

 $oFtp = new Ftp();

 $oFtp->connect();

 $oFtp->close();
ts01
  • 1,171
  • 10
  • 17
1

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.

23JUL
  • 1
  • 1
  • Are you sure that __toType($type) is better than __toString, __toInt, etc? It makes code less readable (think all that switches inside). And if one conversion, ie to int, is not supported? And how can you validate return type in that case? And concerning __fromType($instancetype), how do you know target type in this case? – ts01 Dec 27 '10 at 07:03
  • Well, I admit I didn't think it through that well. The main idea of (the static) `__fromType($instance)` is that it could resolve in constructing an object from another instance lacking (or explicitly returning null through) a `__toType($type)` method e.g. `$f = (FileInfo) 'path/to/file';`. Concerning `__toString()`, I would rather see the other primitive types as well though that doesn't solve object casting and in the case that I should be careful what I wish for: I rather ask for something that rules them all. – 23JUL Dec 30 '10 at 14:32
1
  • 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).

1

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/
Alexey Shein
  • 101
  • 2
  • I think PHP verbosity is a feature, not a problem. It seems nice to type less characters when you type it, it's much less nice when you try to figure out someone else's code. And PHP - unlike Scala - is supposed to be a language accessible to beginners. – StasM Dec 31 '10 at 21:31
1
  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.

Reece45
  • 101
  • 4
  • I want to upvote points 12 & 18 of this post, but none of the others :-). – rjmunro Jan 06 '11 at 23:33
  • @rjmunro Is there a good reason to keep Fatal Errors, asides from "hardware" problems like "Out of Memory"? – Reece45 Jan 08 '11 at 18:57
  • I'm not saying I disagree with the other points, just that they aren't original enough for me to upvote - most of the others are mentioned by other people. – rjmunro Jan 09 '11 at 00:19
1

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

Ming-Tang
  • 856
  • 5
  • 15
1

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();
giftnuss
  • 101
  • 3
0

include better hypertext-links support, i.e. a function/class-method that can be used to change the browser's current-uri. or to create a totally new one. using $_SERVER[ 'REQUEST_URI' ] || $_SERVER[ 'PATH_INFO' ] to understand the resource that is requested. This might make something like developing REST-apps easier. ( according rfc's UriScheme and it's default scheme implementation, maybe make it possible to implement other UriSchemes extending the UriBase)

Provide something like a UriResource class, enabling requesting small snippets of functionality in a way that could also benefit http-requests from a client.

Make a function that can be called before and after a template, enabling short-tags between those two function-calls. Between those function-calls the only variables that are made available are those passed to the first function-call( as associative array( using extract)). This might ease template-development in php itself( no-framework framework). The no-framework PHP MVC framework

All in all i think the many php frameworks out there have certain similarities which could easily be integrated into php in a common way.

but whoami :)

0

I like the php progress and scalability in the recent days.

The new features introduced in java have only make the things complex rather then making it simple.

request 1: db-connection-pool facility as additional library.

request 2:

I am asking for the reverse ajax or comet programming or RTMP facility as a built in library.These are already developed for .net,java, python and perl by dojo foundation

We have similar things in php but not a complete solution.

  1. Also there is support for observer pattern in SPL. but not properly documented.
  2. Xajax framework (good but it requires redesign the application)

bye for now.

0

I really would like to have annotations.. afaik that RFC has been dropped.

0

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
0
  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)
0
  • 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.
0

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.

gabe.
  • 263
  • 2
  • 6
0

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

0

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.

Tgr
  • 111
  • 5
  • I see two problems with this: 1. relying on engine core implementation is usually a bad idea and 2. Calling function on a value increases its refcount, so it would never return 1. I guess you could do it with explicit refcounting though or by implementing it as PHP extension. – StasM Apr 17 '11 at 07:32
  • 1
    @StasM: how about [weak references](http://en.wikipedia.org/wiki/Weak_reference)? 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
0

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
Christian
  • 201
  • 1
  • 6
0

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.

Xananax
  • 1,380
  • 1
  • 12
  • 14
  • also, short-hand array syntax would rock – Xananax Jun 22 '11 at 05:56
  • I had not noticed this had already been requested (by MicE). I was sure to have read everything though. Well I hope at least my (more developed but more confusing) answer gives someone who has never thought of this feature some insight. – Xananax Jun 22 '11 at 13:44