The new PHP
programming.oreilly.com
programming.oreilly.com
* Namespaces, closures and FPM were already in PHP 5.3
* The built-in web server was already in PHP 5.4
* Improved variadic functions, argument unpacking and phpdbg will be in PHP 5.6, which goes to beta in about a week.
Can you give an example? I googled "closure conversion" but didn't understand.
public function getTotal($tax)
{
$total = 0.00;
$callback =
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
array_walk($this->products, $callback);
return round($total, 2);
}
In other languages that have true closures, the anonymous function "closes over" the lexical scope in which it was declared.Besides, doesn't Python work the same way?
If you don't assign to x, the compiler will do the right thing without help.
<?php
$x = "b";
$b = 42;
echo $$x; // equivalent to echo $b;
// Here the compiler can't determine all the variables
// used in the function.
// Has a result, there were two choices:
// - capture the whole environment
// - capture explicitly named variables
function () {
return $$x;
}
Hopefully, nobody uses variable-variables these days, however this is the reason behind the introduction of `use` for closures.The necessity of `use` is, IMHO, ridiculous.
"The new Java"
It's good to see PHP maturing. However sometimes the most important features of a language are the features you don't add. I think PHP would do itself a big favor by cleaning up its main APIs and standard library first. Maybe they will do that in PHP 6, since I doubt they want to break APIs in minor releases.
However that doesn't work forever, at some point you need to clean up some of the old stuff. That's why a PHP 6 release is planned in the near future (i.e. somewhere in the next three years ^^).
I've since moved on to more well thought out languages, though PHP keeps pulling me back in. I'm currently having to support a CI app that hasn't had a line of code added to it since 2008, and the only thing I can say, even though I appreciate the language and how far it's pushed the web, I'm glad it's no longer my go-to language of choice. Keep PHP5 around for a while so apps like this one can continue on, but PHP6 is _LONG_ overdue.
However due to problems and internal conflicts the effort was stopped a few years ago and there has been no progress since.
If this goal hadn't been stated PHP 5.3+5.4 would probably have been PHP 6 (they have some major new features). Core API cleanup never has been (and it doesn't look like it will soon be) a goal for a future release, unfortunately.
It will be interesting to see if PHP goes that route or not.
That being sort of the problem.
Yes, the PHP core api is still a bit messy due to backward compatibility, but everything else it pretty awesome really. Please take a closer look if you haven't touched PHP in years, before you talk it down.
PHP starts as a fucking mess and gets worse. Maybe once the developers figure out what it is I'll take a look but yeah it's pretty much the developers taking standard features from other languages and fucking them up just like they did yesteryear.
Closures with a use block... even in C you don't have to do that... it's a joke and a mess... How is it that a 44 year old language has better features and less cruft than one 15 years old?
Does it have a ==== operator yet?
Forgot to add your latest variable to the use block? No "closing over" for you.
What's that? All array function are prefixed with "array_"... except for the old ones which aren't, making it both verbose and confusing.
Usage of server-side programming languages for websites: http://w3techs.com/technologies/overview/programming_languag...
Recently, however, I had to get in there. This was a few days after I upgraded my local environment from 5.3 to 5.5. I've been writing Ruby for fun for a while now, and I love how I almost never have to look API related questions up, at least in comparison to PHP API questions. So I just wrote some PHP without looking up whether it was going to work, and it worked, first try. That rarely happens. Then I pushed it to dev, which is still on 5.3, and took the (dev) site down. Turns out the feature "array function dereferencing" is not available in 5.3, so I had to rewrite my code a little bit.
Point being, I could see myself liking PHP more when we move to 5.5 in all our environments.
I'm a Drupal dev at my day job, application dev at home. I love getting into my codebase for my sidejob, but D7 is awful under the hood. PHP isn't what makes it messy, it's the procedural hook system.
And yes, PHP 5.5+ is awesome to have.
Go, recently I've been using it for certain services and APIs. Really great for concurrent programming for services, syntax is nice too.
Python, I've used a few times over the years and have used it with personal projects a number of times. Still like python quite a bit.
(Bonus: nimrod, which I'm helping build a new type system for, Clojure and Scala I've played with extensively but never had a chance to use in production, and C/C++/Vala I've used when doing desktop programming on Linux for Elementary)
Modern PHP is not the PHP of yesteryear. With Composer for dependancy management and sticking to the PSR's you can build very stable, testable, and modern applications that change minds about PHP.
Things like object type hinting can help building stable apps but imho it is still the work of the programmer that can break or make it.
PHP users need to keep it together and set a common base, a standard library with sane defaults.
I don't see how this is different from gem install pkg.
I haven't finished the article yet, but really? Is that what PHP needs? A built-in web server? It strikes me that adding more tools that incompetent web developers can abuse is what got them there in the first place.
How long until we start having security releases for the PHP web server, because so many clueless devs decided to launch and run their site with it?
I have been under the impression that that was, in fact, one of the reasons PHP has such a bad reputation (rightly or wrongly).
> It strikes me that adding more tools that incompetent web developers can abuse is what got them there in the first place.
This is profoundly ridiculous. It's the equivalent of saying Home Depot shouldn't sell power tools because some do-it-yourselfer might saw his foot off.
Just because a tool can be misused is not an argument against it nor its inclusion.
I used to believe this, but now I couldn't disagree more. People can and do misuse things all the bloody time, and the more you enable them to do that, the worse your tool is. How people use what you make is every bit as important, possibly even more important than the technical merits of what you make.
I'd rather a builder use a second hand hammer to nail something than try doing it with a jackhammer.
This is an excuse for educating people, not an excuse for kneecapping the majority due to an ignorant minority. This is the kind of thinking that plagues the GNOME3 devs and gets ridiculed so often around here. The user is an idiot so let's remove features.
I don't see many people harshing on Rails for the inclusion of WEBrick.
In terms of avoiding accidents I agree, but in general, I don't like this kind of thinking.
One man's misuse is another man's hack. The flipside here is that the more you limit and subdivide a tool, the worse your tool becomes.
I'd also rather see builder using something else than a jackhammer to nail stuff, but then I also want him to have access to one if he needs it, and I strongly want people to stop shouting "omg you can't use X to do Y, because X was not meant to do Y". First principle of hacking: tools do not have inherent purpose, they can be used to do whatever we want; they only can be better or worse at a particular task. The world didn't collapse into logical contradiction the last time I cut pizza with a sound card, because of lack of any other sharp tool nearby.
I've yet to see an article that would argue that its existence is a proof that you should be using Python now.
I don't see why you decided to pick a fight about Python, though - Python seems to be a sore point for PHP defenders and I really don't know why
By that measure, PostgreSQL is a horrible database. After all look what happens when I do this:
CREATE TABLE foo (
id serial not null unique,
bar text primary key
);
CREATE TABLE foobar (
chunk_id serial not null unique,
foos foo[]
);
INSERT INTO foobar (foos) values (array[row(1, null)::foo, row(2, '1323')::foo, row(3, '2222')::foo]);
select * from foobar;
I mean my gods. Such horrible misuse of a relational db!Unless the web server displays a huge red message every time it is run saying "Don't even think about using this in production" you can bet that it will be.
Uhh... this is the first line the web server spits out:
PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
The manual isn't exactly vague on this point either:
http://us3.php.net/manual/en/features.commandline.webserver....
So we got the warning already in there, what else would you like?
So the server outputs a message. Great. Is it huge, red and says "do not use me in production"? No. Its a standard version banner.
Maybe we should add some <blink> and <marquee>?
Compare these two screenshots: http://i.imgur.com/Kzdphar.png http://i.imgur.com/CQnU8aG.png
A simple bold tag immediately draws focus and ensures that the huge majority of people who view the page get the important message. That's not being hard to please, it's just common sense.
Doing that would mean the dev/prod environment is different, which is not that great of an idea. Keeping them as similar as possible leads to less chance of "but it worked on the dev server" sort of problems.
You're incorrectly characterizing the argument: it's actually like saying Home Depot shouldn't sell power tools without safety guards, fuses, emergency shutoffs, SawStop, etc. PHP has a number of misfeatures which make it extremely easy for all but the most vigilant of developers to make mistakes with security consequences (https://eval.in/108854 was making the rounds just this morning) or simply increasing the likelihood of creating bugs (i.e. the inconsistent parameter ordering across the similar array_* functions). Most of these complaints date back to the late 90s but now are much harder to make both because the core developers don't take them seriously and because there's now a huge backwards compatibility problem.
The most interesting development in PHP is the HHVM hack mode or similar concepts where an actively-maintained codebase can opt-in to safer behaviour. For the sake of anyone who has to secure code on the internet, I hope this catches on.
EDIT: See slide 15 onward in http://www.slideshare.net/skamerman/ipc-2013-high-performanc...
Maybe how you test for equality shouldn't depend on an ini file... just sayin...
Perhaps testing for equality doesn't need a 3 page answer... in most languages it's a pretty straightforward answer... primitive types use == and objects use either isEquals or operator overloading.
EDIT: To clarify, a framework like Rails definitely has a place for including a web server.
Now Ruby has a lightweight web servers in its standard library (but not its core library). Maybe the problem people are seeing with the web server (and it's not a new problem) is the way PHP's core library contains so many things that other languages would leave out as optional includes.
So it's more like `python -m SimpleHTTPServer` than the node http module.
Before : Install php, write php, install apache / mod_php, refresh.
After : install php, write php, refresh.
Nothing else.[1] no need to install/configure a complex standalone server, focus on embedded thus more cohesive routing systems instead of fragile rule-on-top-of-regexps as seen in apache.
Also, I've really got to stop reading the comments on PHP threads here on HN. They're repetitive, pointless and negative to the point of blindness. I'll go back to building cool things in it (and Go and Ruby and lately C, because while each of those have their issues they all serve a purpose and do it well).
Replace everyone's symfony security/auth module? what could possibly go wrong? :D
Regardless of what anybody thinks about Ruby developers, I've never heard or seen that "people launching production sites with servers intended mainly for Rails development use" is/was a widespread thing.
I don't think I've ever heard of new PHP devs "launching with the built in web server". Django has shipped with a built-in insecure web server for years and no ones crying to fix it.
There's things to fix in PHP, but this is not one.
* Make the "stdout == response body" an explicit option, and make a rendering engine the default instead. Just sending all output is a senseless DEFAULT.
* Remove all the array_x functions and turn arrays into a class instead, and change the parameter order to be consistent across all the functions. A similar action could be done across many other classes of functions, too.
* Tighten equivalence requirements, == should work like ===.
* Etc.
But I always realize I'd just end up with Ruby or Python, both of which already exist and have fantastic ecosystems. Oh well.
Then why not use === ?
... and sadly constitute a large majority of PHP users.
Unfortunately, the biggest hurdle at this point is reputation. No full or dot release will change that.
Why? It's a primary differentiating factor for PHP, and one of the cornerstones of its popularity. Given that it powers a non-trivial percentage of the web, from single page "hello world" sites up to multi billion dollar ecommerce sites, I'd say 'fixing' that one aspect is not something that needs to be.
"== should work like ===". Why? If you want ===, use ===. But given that HTTP, the lingua franca of the web, is typeless, and PHP is targeting web developers, having a language that doesn't enforce types in all cases isn't all that bad.
2: PHP, however, has types. == is wildly unpredictable
2. PHP is dynamically typed, like many other languages, and so you just have to know what types something can be and how they behave together. Even in a statically typed language you need to know how type conversions work. That's what the documentation is for ( http://php.net/manual/en/language.operators.comparison.php ). It's not "wildly unpredictable", it's defined and deterministic.
And not every project needs them.
PHP has been wildly successful precisely because it can fit in entirely small use cases, as well as big cases.
Someone who needs to create a dynamic footer with a "copyright $year" in it... has no need for MVC, routing, templates, version control, etc. They just don't. It's precisely because PHP has a default content-type output of 'text/html' that this sort of 'throwaway' functionality can be done with PHP and pretty much no other language. Not that other languages couldn't do this, but everyone seems to turn up their nose at this market. And yet... this is where the majority of the next generation of developers (and the current gen, and the one before) come from.
It's far too entrenched in too many operations to be easily replaced. Perl didn't get that foothold, simply because there weren't as many developers or websites back then. Well... "simply" - there are myriad reasons why Perl didn't retain its early mindshare and install lead.
To say nothing of the innumerable medium sized businesses that use these kind of "throw away" techniques to generate vast revenue. Companies that were profitable long before node or mongo entered the collective vernacular and will likely continue to be profitable long after they've faded from popularity.
Predictable !== well defined. If you have to look through a chart for equivalence, it's unpredictable to the programmer. But this is a theme for all of PHP, you can't deduct equivalence, function names and function arguments orders, you have to memorize or peruse the manual. Sure, it works, but it has drawbacks.
The requirements for a huge (often overgeneralised) enterprise application are very different from a little script for personal or small-community use. There are far more of the latter than the former, and those wanting to "get started with web programming" are going to start out with that too.
Do you think that PHP is the only language where developers look to other practices in other language communities to learn different/new/better/changing practices? Every good developer is aware of patterns and structures in other languages/platforms - I dare say it's almost the definition of a good developer. I would not regard a Ruby developer who'd only ever done Rails projects as a 'good' developer, regardless of how clean/elegant the code seems.
2. I wonder if reliance on == has ever caused any major security issues? I know there's some edge cases, but I can't remember a time == ever came back to bite me. (Yea, you can point to strpos(), but everyone knows that example and it's marked with a big red box on php.net.)
How is that a bad idea? IMHO much better by default to be outputting verbatim instead of silently changing the output. Escaping is something you should be conscious of, since you then have a better idea of where you need it and where you don't, and what type of escaping you need.
They tried to do escaping on the input by default with the magic quotes option; that didn't turn out well.
It's deterministic. It is by definition not unpredictable.
He meant `$arr->length()` and such. Array access like `$arr[42]` is proper.
Being a PHP developer myself, I can't refute that only selling point of PHP, albeit, a major one, is its so "easy" to get things done. I feel in the near future, with advent of tools to make mature frameworks more accessible, PHP would cease to be a tool for any serious web development.
The cases where PHP is not appropriate seems to often be known before going into it (with notable exceptions like Facebook of course) but thats a success problem not a fundamental problem with PHP.
In 95% of the cases PHP seems to be exactly the best possible, easiest to get up and running, versatile for web based programming.
(Mine has dynamic ORM (reads db schema), a console (REPL that loads project config and autoloader file), and similar project layout. Recently added REST API system that generates MD and HTML documentation at /path/to/project/help/.)
Anyway, I would say the main selling point is ubiquity. Every cheap host I've seen people (clients and semi-technical friends) use supports PHP. It often takes more work to get a Ruby project running on those hosts. Or worse for a Node project.
With blackjack and hookers? Please say with blackjack and hookers.
Thats a joke right ? RIGHT ? PHP probably has one of the best, most mature and versatile selection of frameworks there is.
http://www.google.co.uk/trends/explore?hl=en-US&q=laravel,+s...
CodeIgniter does not have the largest community by any stretch, and its falling fast. If it hasn't already died, then it will in the near future.
Sorry, but based on your comment I don't think that you really know much about the PHP framework landscape.
If you haven't been following Laravel 4 development, you're entirely missing out on a community that's bringing the love back to PHP.
The core PHP community is extremely knowledgable; you're just not interacting with the proper subset. If you take a look at the conference circuit, you'll see a group of passionate and experienced developers willing to share their knowledge.
Check out some of the works pointing the general populous in the right direction:
http://www.phptherightway.com/ https://phpbestpractices.org/ http://phpsecurity.org/
Just looking for a simple MVC app? Silex (http://silex.sensiolabs.org/)
Want something that's beefier and more rails-inspired? Laravel (http://laravel.com/)
Want MVC but near native PHP performance? PhalconPHP (http://phalconphp.com/en/)
Building an enterprise application with a team of developers? Symfony (http://symfony.com/), Zend Framework 2 (http://framework.zend.com/)
..and I'm only listing the more popular frameworks that I know of that are mature. Every single one of these has full unit test coverage, and most have very clear examples of how to unit test your code.
I like that I can pick from so many frameworks instead. This allows me to choose a framework that fits my problem, instead of fitting a framework around my problem. I find this to be one of the highlights of the PHP community, not one of the downfalls.
If you're operating on a massive enterprise scale, it's probably not going to be good enough for your hardware. The HipHop VM might be a saving grace if you're already built on PHP, but pragmatically it's probably a better idea to choose a more matured solution (probably something on the JVM).
If you're doing something that is algorithmically intensive (video encoding as an arbitrary example) PHP is going to be a bad fit.
However, if you, like the vast majority of developers, are working on a website that's main technical purpose is to store data of some sort to a back end and retrieve it later for display and you're not yet operating on a large scale (1M+ users) then PHP itself is probably not going to be your bottleneck for a long time.
If you're a fan of benchmarking, techempower does a good job of unbiased comparisons (although keep in mind these are just benchmarks. It doesn't account for how a particular language or framework is optimized for): http://www.techempower.com/benchmarks/
The key flaw in the PHP community are people like you. People who still think that Codeigniter is THE PHP framework (it hasn't been for at least 3 years) yet still have the nerve to look down on newbie programmers.
The ignorance in your post is embarrassing.
An year or two before the trend was all 'yii' which I though could be 'one framework to rule them all' but after that comes laravel and yet more fragmentation. Yes, I shouldn't ignore that how nice they are but the problem which I see is always the community and with a new one every year, it ain't helping.
PHP is a mature webdevelopment language that features an easy to learn, read, and develop feature set. Scala or Perl are not. (See Perl 6) So I don't see how emulating it will provide any form of benefit. Picking up a language feature because a guru attacks PHP because they can write a feature X in Y lines is almost an immature.
The reusability and performance issues were genuine, but these were to be expected given version iterations and the fact PHP introduced namespaces a while back.
That's like saying a company no longer uses Ruby because they use JRuby now.
Is that really what you meant?
PHP as a choice for an enterprise? Jesus. Could somebody show me a 2-3 year old PHP project which doesnt have code rot? To even speak of 5 year old code that is still readable and somewhat maintainable.
Java is where its at for the enterprise.
Besides a nice modern languages vs PHP. I know what I would choose.
So, no, you're not necessarily stuck between these two options (or Java, which is another popular choice in the enterprise scene). Scala was chosen specifically, among other things, because Twitter had a lot of Ruby developers who would cringe at the idea of PHP, Java, or .NET.
I don't mean a Ruby or another vastly different language.
I mean a language similar in approach to PHP, but with the gotcha's removed, some order and consistency introduced into the API, and a few changes to the defaults. Open source, free, and on all major OS's.
> I'm proud to release the result of a Facebook-sponsored study on the feasibility of using the RPython toolchain to produce a PHP interpreter. The rules were simple: two months; one person; get as close to PHP as possible, implementing enough warts and corner cases to be reasonably sure that it answers hard problems in the PHP language. The outcome is called Hippy VM and implements most of the PHP 1.0 language (functions, arrays, ints, floats and strings).
But it was cleaned up, and mostly incompatible - after all all the commands had changed from cvs to svn :)
A cleaned up PHP would be interesting but it would need a truly killer app. Basically make a PHP clone except for the bad parts. I'd say that the killer app would be a very to use framework that provided various security best practices already built in.
And a PHP clone would need a 0 installation process - no messing around with shell commands or root access. Just copy your .phpclone files and you're set to go.
The big thing PHP has going for it is the huge amount of open source software, and the number of webhosts which support PHP by default. Most of the webhosts can barely keep PHP updated, and the ones who don't, justify it by wanting to avoid breaking backward compatibility with open source software.
Getting widespread adoption for a PHP alternative would be a serious feat.
Look at Py3 vs Py2.
At the end of the day, the way I see it, the true advantage of PHP was its lower barrier to entry. Now that this has mostly been resolved via PaaS hosting, it seems to me we're moving to a word where Node is the new default, because Javascript.
These people will be the death of all of us.
[0] https://www.sellvana.com/blog/on-composer-psr-and-namespaces
The new libs'n'tools are nice; good to see them showcased. But the bottom line for any developer should be to avoid it --like Perl-- for any from-scratch code. This is a legacy language now.
-- Matthew Butterick, RacketCon 2013
Given that it doesn't have one, python beats it easily.
And there are some REPLs with tab completion: https://github.com/ErikDubbelboer/php-repl
Regarding Zend Engine, does anyone have a link for just how much 'less'?
1. Developers complain a lot, and that's a good thing. While it can seem unproductive at times and devolve into flame wars, the truth is you're not likely to choose this profession if you aren't curious and care about the right damn thing happening.
It's just a byproduct of what it takes to be a good dev. We research, we understand, and then we want to stand by our opinions because of that research and understanding. But we can also get lost in that sometimes. It's important to have pragmatism in our toolbelt.
At the end of the day, core maintainers or contributors make sure to cherry pick the best from those arguments. Pull requests are made. Merges happen. Things improve. It's not always pretty, but discourse is like that.
2. The world isn't perfect. Neither are languages. PHP has its share of rough spots, but then it's how you use it. We've all seen some truly awful Ruby on Rails code, just as we've seen some solid, testable PHP code. Your job is understand the deficiencies of a language (any language!) and craft the best code around those limitations.
3. Shiny new things give us blinders. The antithesis to ad hoc PHP might be Ruby on Rails. Yet people discount some drawbacks that are unique (from PHP) to RoR. Do generators, which are encouraged, really help teach a programmer about how their application stack is operating? Maybe you could tell someone to avoid scaffolding. Is Rails faster than well-architected PHP? Hell no, but maybe you could teach someone how to tweak middleware or use JRuby. But you'll notice the same pattern I mentioned in #2: understand deficiencies, create workarounds to those limitations. It's not unique to PHP, or any other language/framework.
And finally...
4. When you are building things meant to be consumed by the general public, more goes into a language decision than the features of that language. You might, for example, have a business requirement to hire up and move very quickly. Are you going to round up a bunch of seasoned, veteren Go engineers in a few weeks to build the next sprint of some great app? It's probably not impossible, but it's not likely either (today). The trick is to solve the problems you actually have.
I'm not advocating everyone use PHP. I'm advocating everyone use the language that best suits their personal or larger business needs. If you care about improving PHP, help make it better. We, the general dev community, are all too busy, considerate, awesome, hard-working, friendly, and creative to spend much time on flame wars. :)
Because it suits and is made by that niche, copy-pasted "solutions" and monkey-ing others, just as the latest versions of PHP try to monkey other language and framework thinking, shows a profound character of its community, monkey-patches thrown together to look like some thought was put into it.
It is not the language of the future, its not where inventions happen.
Its still the same old to its core, pieces cobbled together to look like something it isnt, trying to hide the inconsistencies in its core.
Which is really kind of the problem with PHP. All of that broken stuff was allowed to be broken for so long that it's effectively impossible to fix it. All you can do is layer on more features.