Why PHP Was a Ghetto
codefury.net
codefury.net
I should very much like to see that argument.
My impression of PHP documentation (after using it for three of the last five years) is that it's a endless pile of bullshit whose primary content is in user comments on the doc pages.
That's the core library. Third party libraries are typically wholly uncommented and undocumented.
There exist so many third party libraries because of the low barrier to entry. But as more people join the party, the party moves toward the average. The average third party library is an untested and undocumented mess. I do not think this is specific to PHP.
If the average PHP library is untested and undocumented, they're a couple steps ahead of the average Wordpress library.
(also, I might say, the Wordpress documentation is horrific. Hell, the entire structure of that project is horrific to work within. It's built to be easy for noobs ["the loop"], but makes it difficult to keep anything organized or nicely packaged)
People who don't have access to anything are delighted to have something. Therefore, PHP gets a foothold even though it's lower quality. This is the beginning of disruption.
The next part of disruption is improvement. And PHP is improving. At the same time, other programming systems are improving - C#, python, ruby, objective-C even Java has improved (generics etc). So it might seem that PHP will never catch up - which is probably true. But the crucial disruptive insight is that it mightn't need to: programmers might not all need all the extra improvements in mainstream languages, for all tasks. One piece of evidence is that PHP itself is already good enough for some tasks. For any advanced functionality, it's often possible to think of use-cases that wouldn't benefit from it. This means that it's possible for mainstream languages to "overshoot" what most programmers require for most tasks (to "overserve" them, like serving more food to someone who's already full). But, you might say, mainstream users are increasing in their ability to use advanced functionality as they learn more, so they can use the extra functionality (the patrons' stomachs are getting bigger). The interesting possibility is that the rate of improvement of mainstream languages may be faster than the rate of increase in the ability of programmers to use it (the servings getting bigger faster than the patron's stomachs are) - disruptive research has found that this is usually the case. It's because companies developing competitive products work really hard at improving them (to remain competitive); but consumers don't like to change their behaviour that fast.
The final stage of disruption is that programmers leave their mainstream language, and switch to PHP because although it's not as good, it's good enough for their task, and it has other benefits (not sure what they are for PHP, but for disruption it's usually: cheaper, more convenient, simpler - the latter two are true of PHP, but as it adds functionality, it would seem it must lose them. It will just copy mainstream languages).
But I can't imagine this happening, so therefore either disruption doesn't apply in this case (perhaps because a company isn't running PHP? Or because programmers themselves are unusually competitive and early-adopting, and even if some don't want to change their behaviour that quickly, there's another generation coming up real fast? Or as I said above, PHP can't retain its simplicity of being a template language while adding advanced features) - or my imagination is lacking.
It is clear why hackers get frustrated with the language. It is inconsistent and extremely tricky if you want to write secure code. The core developers are mostly concerned with endless discussions about adding buzzword compliant features that don't add any real value (Zend seems to be obsessed with being a poor man's Java so they can sell their ecosystem to "the enterprise"). Also, the community is pretty mediocre with an awful noise vs signal ratio.
So if hackers don't use PHP, who does? Clearly, PHP is very successful with people that want to tweak open source applications like Wordpress and aspiring developers or non-technical people that want something accessible that runs everywhere. Also, PHP developers tend to be cheap labor. There are plenty of them around, including in low cost outsourcing centers, that will charge you a lot less than more competent developers would. So it seems ideal to non-technical businesses looking for a cheap way to add some dynamic features to their website. Thankfully for PHP this group is a lot larger than the hacker community, so the language won't go away any time soon. Especially if you consider the fact that a lot of hackers learn their trade by writing little PHP scripts and customizing open source applications like Wordpress before moving on to something more interesting (I have to admit PHP was my first web scripting language too, back in 2000, but I quickly moved on to Python and now Clojure).
Is this disruption waiting to happen? I don't know. In fact, PHP seems to be trending downwards[0] as the generation that picked up the language before frameworks like Rails and Django were available is switching to the current languages du jour. If anything, it is not the language that is causing disruption, but applications like Wordpress that are easily accessible to non-technical people. However, hosted/SaaS alternatives like Posterous seem to be disrupting the whole idea of non-technical people installing Wordpress (at least I hope so[1]).
[0]: http://www.tiobe.com/index.php/content/paperinfo/tpci/index....
[1]: The main reason I might sound bitter about PHP is having to extinguish fires caused by idiots who write insecure PHP scripts or install open source scripts without bothering to periodically apply security fixes to counter the constant streams of exploits in said open source code while being responsible for some virtual hosting servers several years ago.
PHP developers tend to be cheap labor
I also hate the term "X developer". I never labeled myself as a Python-developer, or a Java-developer -- I'm just a developer that happened to learn whatever was necessary.Good developers are getting properly paid, regardless of the tools they put on their resume. Tiobe is also an extremely poor reference for language popularity, btw.
That said, last time I used PHP was 5 years ago simply because it isn't suited for the kind of work I do. Now I work with Python a lot, and with Ruby on the side -- because Python has mature libraries for visualization / parsing / data-mining, it has bindings for every meaningful C library under the sun, and because Python can be made to scale painlessly by means of non-blocking I/O or other tricks (as it's really mature in that regard).
I also like Ruby because its community is something to marvel at -- I never seen so much (focused) activity / cooperation and so much work done in so little time.
That's the problem with PHP -- technically, it's just an Apache plugin, done as a quick hack, reflecting in the available libraries / the community's culture, and there's no way it can escape it.
To make a bad joke -- you can pull PHP out of Apache, but you can't pull Apache out of PHP.
An interesting metric would be Google Trends[0], which shows a steady decline in search volume for "PHP" while the graph is a lot flatter for e.g. Python[1]. I don't think the number of Github projects for PHP is a great metric, because I think the Github community isn't representative of the typical PHP user, whereas it is virtually part of the DNA of e.g. Rubyists.
You're right to say that plenty of good hackers use PHP, but not because they think its a fun language to work with. You make a point out of PHP being the right tool for the job in certain scenarios, but in my experience it seldom is. Others have already made the point that cheap hosting isn't exclusive to PHP (consider e.g. cheap virtual/cloud hosting like AWS and Heroko). I can imagine using PHP for quick <10 line hacks when convenient[2] or to maintain legacy code and customize open source applications like Wordpress. Rewriting every line of code in existence using the popular language du jour simply isn't realistic. However, that doesn't make PHP the right tool for the job for fresh, non-trivial projects.
You're also right that good developers who happen to write PHP tend to get paid well. My point, however, is that there is a lot of cheap labor available that is able to write PHP (most of whom aren't good developers). This makes it a great fit for those customers that like to pay minimum wage for software development.
I understand your frustration about people bashing PHP, because in a way it is a silly example of elitism in this community to look down on PHP and its community. However, while I at least try to remain somewhat reasonable about it, my tone in regard to PHP is based on a long list of negative experiences that are presumably shared by a lot of people on HN.
[0]: http://www.google.com/trends?q=php
[1]: http://www.google.com/trends?q=python
[2]: In fact, I recently wrote a
<?php print_r($_POST); ?>
deployed on my Macbook's Apache server to quickly test some Clojure code making HTTP POST requests.The next step seems to be to disrupt Java enterprise webapps. Although that may not be exciting to a mainstream programmer, it would still be a disruption, and typical of how disruptions move upmarket, tier by tier.
fmw and bad_user have noted many important aspects of PHP, but I was really just thinking of its core idea: templates. PHP didn't originate them (eg bash does it echo hello $name; C has printf; etc), but it's taken it to the logical extreme of a program being a template, and it's the most popular embodiment (I think coldfusion and others did it too, but less successfully).
I think templates are a great idea, because they are simple and concrete. Abstraction and other meta features are powerful; but if the job doesn't need them, they only obscure what you are trying to do.
While surprisingly versatile (e.g. TXL does language translation with them), templates are limited as a general programming concept - and so PHP is probably similarly limited, perhaps to just the web (maybe it could expand to desktop applications, since they increasing use HTML for UIs - though deskapps are seemly being disrupted themselves by webapps). But it's hard to seriously entertain a fps in PHP; a compiler (though consider TXL...); a VM; a RDB; mathematica; pagerank implementation; numerical simulation; an OS.
Meanwhile, the template "technology" is accessible from other languages: python, ruby, java etc all have a broad choice of templating engines for webpage generation. So it is arguable that the technology of templating has been co-opted by the mainstream - although, PHP remains the simplest one. When the job is simplest enough, it seems PHP will win, simply because it can do the job, and it is accessible to more people.
BTW: the factors others have mentioned are also important (low cost hosting, labour etc) - though some of them can be traced to the simplicity and concreteness of templates (which made webapp creation possible for people with less skill).
I have to admit, I am a huge fan of template "technology". I think it is a brilliantly insightful and simplifying idea. They can also be seen as productions in a CFG.
That's completely silly. Every setup I have right now is Nginx and php-fpm, neither of which have any relation to Apache or, indeed, any relationship to any other aside from communication to php-fpm via FastCGI.
These generalizations are really funny, because they demonstrate a lot of the misconceptions about PHP and its community.
All generalizations are worth precisely nothing, including this one.
Personally, I'd like to see them start with example code, and then highlight a few of the more important functions, and THEN get into the gritty details.
As it is, I'm about as productive just dir()ing everything in the interactive shell, and then seeing what happens (sometimes falls down with passing options, though), and that's almost as good as the docs.
PHP though? Yuck. Although it's tons better than Joomla's documentation.
But the real reason I wanted to comment: stop dir()ing through modules! Install ipython and learn to use ? and ??. Life will be so much easier.
Edit: Checking it out now (actually already had it installed, thanks Ubuntu!), the ? and ?? things are just awesome.
Agreed, but the user comments include a huge collection of common problems and their (mostly) quick n dirty solutions. This is a part of what's making the language so accessible for newcomers. Of course it doesn't necessarily encourage best practices.
The python documentation is an example of good documentation. And again, it's tied to the language's culture, where documentation has a really high priority.
I'd often like a stronger emphasis on the types of arguments and what gets returned.
I don't know enough about Java documentation.
I hardly memorize stuff 'cause it's so easy to look up to the docs that it's not necessary. And here is what you get when you don't really know what you are looking for:
That is just nice documentation...
An example: http://clojuredocs.org/clojure_core/clojure.core/condp
'Array function parameters are ordered as "needle, haystack" whereas String functions are the opposite, so "haystack, needle".'
I noticed that too, and it floored me.
I think i could forgive php more for behaving (and being named & structured) wildly inconsistently were it not that the documentation tries to make up for this by pretending this is actually not the case.
So not only do you have this issue where the behavior of a function may be erratic but the documentation attempts to gloss over the issue by describing a function's most optimistic outcome rather than its actual behavior. Any behavioral caveats are left in the Notes section which in any other language documentation is reserved for "not thread safe" or "uses an easily guessable seed" or "execution blocks network access". Instead the Notes are used to explain "optional arguments not included change the behavior of this method to behave like this other one, but give no warning or otherwise visible indication of error."
The whole "php is defensive programming" statement holds because you can't trust the documentation to be upfront about inconsistent behavior.
The two have so very little in common they might as well be using different languages.
I'm oversimplifying of course. There are a number of large an quite successful communities that fall somewhere in between, like Drupal. The point is, neither the communities nor the code they write have much in common other than having PHP somewhere deep at the core. There is no "this is what PHP is like" anymore, and that hasn't been the case for over half a decade.
A couple of asides as well, sapphire, SilverStripes framework has now been spun off as it's own, independent php5 framework https://github.com/silverstripe/sapphire. Secondly, his mention of CodeIgniter got me curious again, great to see they've finally dropped php4 support. I'm going to have to check it out again I think.
I mention Drupal because I find its "the node is our hammer and all solutions are nails, er content management systems" approach to doing things is a perfect example of the PHP google-then-copy-and-paste programming caricature that is all too often true.
But the author's correct: to the extent that PHP sucks, it sucks not because of PHP itself but the culture that surrounds it. In my experience, everyone's a noob, an advanced noob that is eager to share their bad habits, or callused actual experts who assume that you are one of the aforementioned noobs and assume you have the cognitive capacity of an overripe banana.
I know several PHP developers who I respect—Hi, Sunny and Tom!—but they seem to exist outside the PHP space-time continuum.
I don't ever want to touch Drupal again, but not because the code sucks. I just think it's working at the wrong level of abstraction. I understand the need for that level of abstraction, but personally as a UX designer and developer I feel the compromises Drupal forces cheapen my work.
When I talk to people who want to create a content-driven site, I walk them through the three types of web sites I see: those simple enough to be comfortably implemented using WordPress, those that are more complicated by still simple enough to play to Drupal's strengths, and those that are more complicated or are expected to be more complicated over in the near to mid term and thus call for a Django (my choice) or Rails or whatever application.
When I picked up Rails, everything clicked right away because it directly addressed so many of the shortcomings of how things were done in PHP. Digging deeper in the Ruby community I found a genuine passion for pulling in great ideas and advancing the state of the art. Ruby has shitty projects too, but the good stuff is more prominent and easier to find.
After 5 years with Ruby I'm not particularly eager to leave, but I do feel the urge to pick up another language to expand my horizons once more. Preferably something with a high density of good ideas, like Haskell.
I know PHP has evolved and is quite capable as a language, but the only way I would touch it again is if I was working on a project that was interesting for bigger reasons (eg. Facebook).
Essentials of Programming Languages http://www.amazon.com/Essentials-Programming-Languages-Danie...
The Little Schemer http://www.amazon.com/Little-Schemer-Daniel-P-Friedman/dp/02...
from watching a recent talk (http://ontwik.com/php/php-performance-by-rasmus-lerdorf/) he gave, i didn't get the impression that he hated frameworks, but more that he hated most php frameworks because they were slow.
in the video he says a big problem with current frameworks is that they deploy to production the same code used in development, which still includes all of the knobs and extra includes that have to be pulled in on every request to support things that aren't used. he would rather see frameworks turn code into a streamlined bundle of code that gets pushed to production.
http://php.net/manual/en/book.reflection.php
And define metaprogramming; PHP has supported all of what I would consider metaprogramming as part of their core API since PHP 4. It may not be as pretty as what you can do in Ruby or Python, but you can do it just the same.
Example PHP vs. Ruby
PHP:
$a = new A();
$reflector = new ReflectionClass('A');
$properties = $reflector->getMethods();
Ruby:
a = A.new
a.methods Java and C# are even more verbose than PHP
but they can also do reflection just as well
as Ruby and PHP can.
Err, no, they cannot -- in Java/C# you cannot create or redefine functions / methods / entire classes at runtime.To do that, you need to get into bytecode generation, and that's not a feature of the language anymore; not to mention problems with the fact that their respective VMs weren't designed to allow the regeneration of methods/classes at runtime, so you run into problems like the permanent-generation in the GC (i.e. classes aren't garbage collected, so if not careful you may end up with a huge memory leak).
"more verbose" doesn't really describe the shit you must do to make available the same tricks you can pull in Python/Ruby.
Comparing this to C + assembly generated at runtime would be stretching it, but just a little -- having the ability to generate assembly doesn't mean that C has meta-programming facilities ;)
The best you can do is modify the class definition in the code itself, and declare a __call() or __get()/__set() functions that park themselves in front of method calls and variable accesses. You can't go re-opening classes or directly adding methods or variables.
(To make matters worse, __call() and friends are also more than a little slow as well.)
I would agree that Java, C#, and PHP lack the ability to do this without a lot of overcomplications, but at the same time, I've never really found myself in a situation where rebinding or extending classes at runtime was really the best solution. I would actually be quite interested in seeing a usage of that sort of magic that actually makes the solution easier and simpler than other options.
I've never really found myself in a situation where
rebinding or extending classes at runtime was really
the best solution.
That's only because you aren't used to it, and you're dismissing it based only on a limited experience with what is possible; although the libraries you're using may be doing it without you even noticing it.If you're a Java developer, what do you think frameworks like Spring, Hibernate, Guice are doing?
And why in the world would you be using dynamic-typing if everything was set in stone from compile-time? Structural-typing (like in Scala) works a lot better ; although I can see why there's a misconception about what dynamic-typing really enables.
That's the thing with half-baked features -- of course they are hard to use and error prone when the language itself isn't really built around it. But in a language like Ruby, where the "class" block's main purpose is to open a scope where "self" (the implicit) parameter points to that class, and inside the definition you can put anything, like real code that does stuff, and where creating new classes (in case they don't exist) is just a side-effect -- modifying classes and objects at runtime is everything you're doing (whether you like it or not). But it does give you the tools to deal with it.
Same thing happens with Python, but more with functions and class methods, rather than classes, because that's what Python was optimized for -- decorating functions with extra behavior, since functions are first-class citizens.
In Python it doesn't work so well for classes, since inside the definition itself you don't have access to "self", but you can also patch classes with great effect, just not with so much syntactic-sugar as in Ruby -- that's why people shy away from it and choose to deal with functions/methods instead, although there is some cool meta-programming stuff done with classes in Django.
That's what decorators do btw (which look similar to Java annotations, but have a lot more bang for the buck :)) -- http://www.python.org/dev/peps/pep-0318/
I would actually be quite interested in seeing
a usage of that sort of magic
http://rubyonrails.org/ -- and really, don't be fooled by all the clones available. I worked with Symfony and CakePHP -- every Rails-clone sucks compared to Rails. You have to try it for real in order to see what it does differently.If you're a fan of Java: http://aspectwerkz.codehaus.org/
See that link above? -- that's so easy to do in Python/Ruby that it doesn't deserve a library ;-)
This is a good read on Ruby's meta-programming facilities, while not being so hard to read btw: http://pragprog.com/titles/ppmetr/metaprogramming-ruby
Also, terms like "monkey-patching" and "magic" are derogatory terms for good engineering practices people have been using since the 70-ties when generating assembly at runtime was the only reasonable way to make complicated algorithms to work, while maintaining some sanity, like those in the field of artificial-intelligence.
In the meantime people got so obsessed with preventing employees from shooting themselves in the foot, that aberrations like C++ and Java happened. Unfortunately for everybody, bad developers write bad code regardless of the programming language.
get_class_methods('A');Look at how e.g. Python solves this:
class A:
pass
class B:
pass
a = A()
b = B()
# only known at run-time:
c = random.choice([a,b])
print c.__class__
No mucking around with names needed. The same applies to functions---like PHP's array_map function which takes the name of the callback as an argument, instead of the function itself.I also don't understand why PHP's syntax treats variables whose type is a function different than variables which have a more mundane type. I.e. nearly all variables need prefixing with a $, but variables which hold a function need no such thing. And you can not assign to those function-variables.
Your second sentence I don't understand - what do you mean 'variables whose type is a function'? The equivalent of a function pointer? For variable functions, you take a regular variable (i.e., with a $) and assign it the name of the function you want to call:
function call_me($arg) {} $func = 'call_me'; $func(1);
Depends on which kind of flexibility you want. You can use a dict of name to type i.e.
d = {"A":A, "B":B}
variable = d[string_from_file] (arguments)
or (perhaps slightly un-Pythonic, I guess) variable = getattr(my_types_module, string_from_file) (arguments)
where my_types_module is a module with your constructors.The second version is somewhat closer to the PHP version, but still cleaner.
The problem with a system like
function call_me($arg) {} $func = 'call_me'; $func(1);
is that it does not play well if you have several different functions of the same name but in different scopes. Or if you want to generate functions on the fly.That's a concern, but not too much of a concern in a language like Python. I only chose Python because many people are somewhat familiar with it, and it does the Right Thing in this regard.
As an aside: Matlab recently changed from a PHP-like functions-passed-around-by-string-name system to functions-as-first-class-citizens system. They even had to introduce a new bit of syntax for that---but they found it important enough to go through with it. (Look at http://stackoverflow.com/questions/796935/function-handle-in... if you want to read about it.)
Right, and how is that more readable or more clear than the PHP equivalent?
$myclass = new $classname; vs variable = getattr(my_types_module, string_from_file) (arguments) and you claim the second is cleaner?
Furthermore you are making several normative claims like 'Right Thing' but don't offer anything to back that opinion up. Function pointers are strongly typed too, does that make them superior? No just different, and I think the PHP way fits perfectly well with a consistent theme: you can substitute any name that you'd hard-code with a variable and it will work.
$var = 'test';
// Call function called 'test' with argument value of 'test';
$var($var);
// Set variable called '$test' to a new instance of class 'test'.
$$var = new $var;
// Call method 'test' on variable '$test' with argument 'test'.
$test->{$test}($var);
Straightforward and no need for strange 'getattr' indirection functions (see how I turned an in itself neutral design decision into a normative statement there?)If you want, we can continue the discussion via email---it's getting a bit unwieldy for the comments here. My email is in my profile.
Thanks.
PHP is unique among its class of languages (counting Ruby, Python, Perl etc.) in that it has an extremely dynamic runtime, but yet keeps the compiletime/runtime distinction known from compiled languages, such as Java.
I have a love/hate relationship to that. On one hand it feels stupid and restrictive compared to more thought-out languages such as Scheme, Javascript or ruby, but on the other hand it _does_ instil some stability in an environment that is quite chaotic in other respects (dynamic-weak typing has some confusing edge cases, just to name one). I'm not sure it's such a bad balance after all.
Could you elaborate on that? I don't see what you mean.
Interestingly, Python usually also gets compiled---though the target language (Python's byte code) is still very dynamic.
As an aside, PHP gets compiled into opcode before interpretation, but the two processes are usually not separated. This is true for most interpreted languages actually.
To me, that sounds more like a flaw in PHP that it doesn't save bytecode and reuse that if the underlying source has not changed, not a defensible reason to claim it is faster than other "similar" languages.
If PHP has a reputation as a ghetto, it's in part because of cocksure noobs like this who think they know everything and are impossible to have a rational conversation with.
If you disagree with @compay, you will assuredly earn the same title.
(Compay has a karma of 1426 for comparison, and I owe him for introducing me to the PIE library for IE CSS)
Based on your comment and that you have a tenth the karma of the person you're accusing of being reactionary, I would recommend that you make an actual argument or mount a defense, and stay away from these kinds of insults.
You can read all about them here: http://shootout.alioth.debian.org/
There's a very obvious reason why a language may be relatively fast today and relatively slow tomorrow - namely, other languages continue to be developed as well.
And now, here's what the point of my comment is. I assume you work with PHP and are unhappy hearing that it's slow. Well, I work primarily with Ruby, which in general is even slower, so don't take offense. :)
Let's take a look at the context of this conversation. You haven't seen any evidence of its relative speed for "several years," and haven't even given the issue enough thought to discover the most obvious reason why its status may have changed, and yet in the face of somebody offering evidence (I did on the OP) are reluctant to accept the possibility that PHP is slow. I've programmed in PHP for around 10 years, starting when 3.0 was in beta up until the first few releases of 5.x, and in that time I've seen many, many PHP developers with this attitude.
This is a general problem of the PHP community: Zend has done a fantastic job marketing PHP, and PHP has been used on so many high profile projects, that developers just assume PHP is "blazing fast," when that's simply not the case.
Now, before I get attacked as a PHP hater again, let me point out that even though I prefer to work with other languages now I am by no means a PHP hater. I just recommended a PHP solution over a Ruby one to a potential client, because in their business context I thought it made more sense and couldn't in good faith sell them a technical solution that wouldn't meet their needs as well just because it used my current favorite language.
I'll also explain where PHP is quite fast. A lot of the functionality in PHP is just a very, very thin wrapper on top C library calls, and has very little overhead. This is why things like math operations are generally quite fast. Facebook's Hip-hop compiler, which precompiles PHP to C++ and then compiles it to native binary, produces code which on some benchmarks performs worse then the original PHP code because of this fact.
But the parts of PHP which aren't just delegated to C code are in general very slow. Consider, for example, a benchmark that's heavy on array traversal. Take a look at PHP compared to other languages and see how incredibly badly it performs compared to everything else:
http://shootout.alioth.debian.org/u32/benchmark.php?test=bin...
TL;DR: 16 minutes for PHP and 268.15 seconds for Ruby 1.9.
If you want to bitch about the fact that that benchmark includes the time it takes PHP to compile the code, well, then subtract roughly 0.1 seconds from PHP's time, but also do it for Ruby since Ruby's benchmark also includes compile time. Opcode caching isn't going to save you here.
Think about this for a second: what do you use more in a web development context: math operations, or array traversal? Just think how much time your web apps spend looping over database result sets. See what I mean? PHP may certainly be "good enough" but please just stop saying it's the fastest thing out there unless you can show me some proof.
If the PHP community had more of a backbone and stopped believing untruths like "our docs are the best in the business" and "PHP is the fastest scripting language" then Zend would be forced to do something about it. The fact that the language, the interpreter, and all the soft infrastructure around it are such a mess is not because Rasmus or Zeev or Andy are incompetent, it's because for years they've had such an incredibly unskeptical community of "true believers" that never holds their feet to the fire on anything. Stop being a true believer. Insist on something better. Bitch and complain if you have to. That's how to improve the programming language you love to use.
I disagreed with your comment because I didn't (and still don't) think it's valid to compare the speed of running precompiled binaries vs. something being interpreted.
Why is that not valid?
1. Java (your example) compiles to bytecode and drops the output into .class files. It only runs this compiled form. 2. PHP natively compiles to bytecode every single run. It does not save the bytecode (or cache it) by default. APC does this.
My point on my blog was that if you're going to benchmark PHP vs. C++ and call one slow in the end, you should at least try and put them on the same playing field.
Think about it this way: Could you make a real decision of which language to use for a website based on those benchmarks? No, and you (@compay) concurred that there are other factors to take into account (like opcode caching). This is why the benchmarks are irrelevant in the context of my post.
And if you still can't understand why opcode caching is irrelevant to the benchmark I cited, then you are being a fanboy.
If you have a hard time believing that your favorite language may have some performance deficiencies that could be improved then you are acting like a fanboy. Simply saying "I'm not a fanboy" doesn't disprove it because actions speak far louder than words.
I didn't refute that PHP has performance deficiencies either.
The only thing I can really say from looking at those benchmarks is that PHP is very likely a poor choice for general purpose (non-web) application development where speed is a definite issue.
When building a webapp although, those benchmarks suddenly because unclear to me because they mask the fact that byte/machine code caching is used for some, but not all languages. That feature is available for PHP, and it's called APC.
That is all.
Sorry, I guess I just assumed that because of the amount of time you've dedicated to writing about PHP on your blog, and the fact that all but one of your projects on Github are implemented in PHP. But sure, maybe your favorite programming language is one you never publish code in, and never write about on your blog. Forgive me for assuming too much. BTW, I never said there's anything wrong with PHP being your favorite language, if it is.
> You're drawing an invalid assertion based on the fact that I've been disagreeing with you.
Bravo, you've scored a point in the argument. However, you've also managed to reduce our conversation from a potentially friendly, intelligent discussion of the benefits and drawbacks of PHP to a competition to cherry pick single sentences and find the tiniest flaw in them, rather than look at the ONLY point I've been trying to make the whole time, which is that PHP's average performance on cross-platform benchmarks is not very good, and so it's not such a good idea to claim it's "maybe the fastest and most scalable scripting language" unless you have good evidence to show why the benchmarks are irrelevant.
In the course of this discussion you've lost sight of the fact that I posted a friendly, supportive comment on your post and merely pointed out one thing that I thought was inaccurate, and you've come at me with guns blazing, telling me to look into APC, which I was already using when you were probably still in elementary school. That's why I called you a cocksure noob.
> When building a webapp although, those benchmarks suddenly because unclear to me
Yep, like I said in my very first comment, I think PHP is often just fine for web apps, because its raw performance in a web context is often not the bottleneck. However, sometimes it is a problem, which is why people have invested the time into creating PHP to native binary compilers, for example. If APC solved all performance problems, do you think anybody would have bothered?
> because they mask the fact that byte/machine code caching is used for some
Stop equating Java bytecode and PHP bytecode. It's not the case that if you simply enable APC, you'll get in insane performance boost in, for example, array traversal. You'll get a significant performance boost in page request time because the interpreter doesn't need to generate the bytecode over and over again. That's it, unless you throw in an optimizer as well.
(That said, full disclaimer: I'm writing a PHP extension in a hobby project for a popular library to use that library from PHP, so in that sense I've moved closer to it again over the last 2 months).
Anyway, my main point was that you said "to point out that PHP's interpreter is in fact rather slow compared to pretty much everything else", which I still don't agree with. On straight pass-through to C calls, the overhead is a lookup in a hash table for the function name, and some wrapping of arguments into a union if need be. Arrays are slow because they're also implemented as hash tables; for high performance, one can use structures with iterators that can skip this step. But these are all just single data points; I haven't looked into the implementation of the tests you linked to, but I guess it's not that hard to find counterexamples. That's the nature of tradeoffs you make.
Your comment seemed to imply that the runtime is somehow deficient, compared to others; I'm still not convinced that is really the issue, especially since PHP is really just C with some wrappers around it. Whereas for example Python apparently does (used to do maybe, I don't know) much more bookkeeping etc for the dynamic features that enable its syntactic niceties. Advances in VM precompilation may catch up with that, but how would it make such progress that it would be faster than the straight-to-C equivalent?
Also your mention of hiphop I don't understand. When hiphop compiles something to C++, and then into machine code, it can only be slower than the original PHP code if it changes the algorithms - which are hiphop issues, not related to the speed of the runtime.
Anyway I wasn't claiming that PHP is the fastest or best documented; I just don't accept at face value your claim that PHP is significantly slower than other languages in its class on a sufficiently wide range of real-world use cases.
(for the documentation, I always liked it - most of it lists the parameters, a simple example and some corners cases, and the comments are great, of course for people who are capable of separating the chaff from the wheat. Actually I think there is still a script in the php source tree written by me that transformed the docbook docs into man page format, so that I could open the docs of the function under the cursor in a split window in vim with a single keystroke; that was in 1999 though and 'parsed' the docbook with regular expressions, so if anyone in their right mind had a look at it in the last 10 years they would've deleted it).
There are a few times when the choice between one language over another is more of a pragmatic issue rather than one of taste, and Ruby's ease in creating DSLs (and hence, Rails) is a perfect example.
As TFA mentioned, Ramsus Lerdorf has the right idea. PHP is a templating language. Contorting it into a general purpose language and squeezing a Web framework out of that is unpleasant when there are so many nicer alternatives available. I almost feel bad for Rasmus; people are using his language, taking it beyond its intended scope, and giving it a bad name for that.
I'd argue that CI is to PHP what web.py is to Python, or Merb (pre-merge? - correct me if I'm wrong, maybe there's a better example) to Ruby.
CakePHP-Rails would have been a better analogy, but my point still stands. The language plays a large role in making a framework nice to use, as much as the intrinsic design of the framework itself.
Eh some people (like myself, and my colleagues at the time) were using those concepts in PHP (albeit that 'routes' and 'helpers' were just called 'mod_rewrite paths' and 'utility functions') in 2000, long before Rails was even conceived.
It's not built around creating DSLs, it's built around using solid OO principles to build a very extensible system. Yii's use of behaviors (much like mixins in Ruby) allow you to easily encapsulate behavior and share it among many models and projects, and of course it's built on a solid foundation of classes and interactions, including ActiveRecord.
I still dislike the syntax a bit, and I understand how the syntax affects the design of the framework, but really it is very similar to Rails.
Once you get the hang of Yii's ActiveRecord implementation (with scopes, behaviors and relations), you're a fair chunk of the way to a) understanding how to use Rails' version effectively, b) coming to loathe CodeIgniter, Zend Framework and CakePHP for not providing similar functionality.
Also it's worth noting that if you do want to do PHP "right" and use a framework like Zend or Cake you will probably still be shopping around a bit because you're not going to get the ability to use those frameworks out of the box on most hosting providers.
Thats huge.
From the article:
| Rasmus represents what most non-PHP developers hate about PHP.
| Rasmus generally promotes abstention from using frameworks, and the use of PHP as more of a templating language. To him, this translates to raw speed and scalability (load-wise). To everyone else, this translates to piles of procedural spaghetti code, and unmaintainable projects. For roughly 10 years following the birth of PHP in 1995, this was how PHP projects were written.
The thing is that it isn't like say 30% of hosting providers offered it and it slowly got more and more, it was more like massive overnight 100% market penetration.
I've never met a hosting provider that didn't provide it, despite the fact that it is an absolute security nightmare.
I'm still puzzled about the nearly instantaneous and complete market penetration of php.
Take your average PHP programmer and force him/her to code in Ruby and the same mess will result.
The fact that PHP has so many "noob" programmer is indicative of its success in creating so many great projects and websites. We have made PHP so easy that even your grandmother can do it.
From the article:
If you are capable of making wise software design decisions, PHP is a great choice to build your web application with.
I'd wager it's so easy that even your grandmother can do it /badly/, while putting her business or data at risk.
More seriously:
Frameworks or languages that make it easy to be secure by default are a lot better, both for newbies who don't know better, or for old hands who slip up once or twice.
The simplest example I can think of to illustrate the difference:
<h1>Hi, <?php echo $name; ?></h1>
vs
<h1><%= name %></h1>
(Say "name" is "<script src=xss.js></script>". The former is vulnerable, the latter is not. Both are just as easy to write.)You simply won't be able to upgrade PHP to make <? echo $something ?> behave properly. That's the problem with languages that were designed to be frameworks in themselves -- languages have to maintain backwards compatibility.
Both the update to rails 3.0 or to a hypothetical new release of PHP which escapes parameters to echo would cause the same amount of work.
What you could say is that rails is less afraid to force change on people and that conversely, PHP puts more emphasis on backwards compatibility.
Both have their advantages and their disadvantages, so this particular issue, I feel, really can't be used to show the inferiority of PHP. Parameter order of functions? Crude syntax? Strange case sensitivity rules? Awful, counterintuitive == operator? Sure. Emphasis on backwards compatibility? IMHO not really.
Emphasis on backwards compatibility? IMHO not really.
It's not that -- I like frameworks precisely because there's a layer of abstraction between my code and the final output.Using PHP as a web framework, without a higher-level of abstraction (like a PHP framework) is dangerous because backwards compatibility has to be preserved.
"echo" in PHP is like "print" in Python. It wouldn't make sense in either case to force escaping of HTML tags for such a low-level instruction. But people have been using it to output HTML content for years.
Changing echo; to encode entities when used from within a web server SAPI (so not on the command line) would not cause more or less hassle per app than changing <%= to encode entities by default.
Of course the overall PHP code base is much bigger than the rails code base, so there would be more people affected. But for the individual application developer, there's no difference in amount of work whether <%= suddenly starts escaping or echo; does.
CI doesn't even have the base class of any "controller" defined anywhere for you to read. It is created on the fly every request. This guy is a noob and doesn't understand what good programming is.
If you look at Symfony2, it can handle both namespaces and Zend-named objects without significant trouble. ZF 2 will change it because namespaces are now available, but the old style of library importing will certainly persist because it has to.
I dislike ZF because it tries too hard to be like Java/Struts2, and borrows a lot of Java's verbosity and bloat.
I use Yii a lot nowadays, and use phing for deployments. And for Python folks, I'd recommend web2py since it has a lot of similarities to Yii from what I've seen.
>Ugly syntax
The syntax is not that importent (the semantics are the BIG problem) but you are right. What to expect from somebody that didn't even want to read a hole parser book (not blaming him i think there boring too but if you don't want to read a parser book implment a lisp)
>Lack of some necessary features that other languages have (prior to 5.3, namespacing, closures)
Having a feature in the language is good but not worth a lot if there not idiomatic to use.
>Inconsistent function naming, usage, and other quirks Inconsistency is te big word. Everywhere. Nobody thought about what is done how, where or why.
>The fact that 80-90% of PHP projects are probably gigantic piles of shit
yeah.
The "good":
> Standards (not universal, but generally a flavor of MVC for most projects, and little procedural crap)
1. Application Design is more then just MVC. 2. Most PHP Code produced still suckes. Sure there are frameworks and standards know but how many % of the people writing php know this? I know lots of people how get tough php just like 10 years ago and if they are not really into programming (like people here) the will never learn the good stuff.
Having "Standards" and people using them is a diffrence.
>A very low barrier to entry True. Php was just at the right place at the right time.
> Speed & Scalability (maybe the best among script-based languages)
From most benchmarks I have seen php was really slow. Isnt it compiling to bytecode witch then gets inerpreted?
There are projects like HipHop and phc but I havn't seen really good numbers for them.
Are there good up-to-date benchmarks to support this?
> A great unit testing framework
What language that could has somewhat the same scope as php does not have really good testing frameworks?
> Arguably the best documentation for any language
Read some compents in this thread to see peoples opinions on that.
I have quite a lot of experience using PHP under heavy load, and i know for a fact that Ruby or Python are no match to it, and .net is barely better if not equal.
As a PHP developer, mainly (i also enjoy Python and C), i am aware of a lot of the problems that PHP has, but in the hand of a developer that really understand the language (attend a couple of conference from Rasmus and you'll get an idea on how to develop PHP properly, and that doesn't mean not using frameworks), PHP is really powerful and unmatchable in terms of easiness to use, scalability and speed.
That said, the high art of PHP was always to make really performant apps while having your code as organized as possible. These days, this is being done very well with files, autoloading, and opcode caching. If you do things this way, Rasmus would be happy, and things would be fast.
I am a PHP developer. A lot of what I saw in the past few years was frameworks like Cake and symfony that basically copied Rails or brought some heavy techniques with a lot of overhead. This is not the PHP way. If you want to see a framework that does things in a more PHP way, I would humbly submit my own:
It's open source. It's called PHP On Pie for a reason: because it's easy and it uses real PHP techniques, not tries to emulate Ruby or Python. PHP has its own beauty, such as arrays which can support numeric and string indexes at the same time.
All this said, these days PHP is outdated for large sites. Not because there is a lot of crap written in it -- which I agree with. But because it still works only synchronously, and the culture is too server-heavy. Large sites should be written like this:
Clients (browser, etc.) do most of the interface logic.
Components should render themselves using javascript, and only use the server for data
Server does web services (REST, socket push, etc.)
Server should not have to do things synchronously.
Node.js rocks in this respect. Unlike PHP, I can literally issue 10 independent queries to 10 different databases and combine the results as they come in. In PHP, I would have to issue this stuff sequentially. That's slow.The second thing in PHP is fixable. People should move most of the logic (that doesn't need authentication) to the client side, and then write all their web services in a very simple way. Stop generating all your HTML on the server. Check out
http://weblog.rubyonrails.org/2011/4/18/why-http-streaming
and
http://www.facebook.com/notes/facebook-engineering/bigpipe-p...
Rarely do I actually spit on my keyboard.
Not only do most other languages do associative arrays properly, so, you know, numeric and string indices don't clobber each other, but they also don't explode when indexed with, say, anything but decimal literals. You seriously think this is beautiful behavior?
The advantage of php arrays (imho) is that you can treat them as associative arrays or not dependening on the situation. The lookup behavior is the same for both though, which is convenient.
i don't know python or ruby enough to compare, but it is nicer than javascript where associative arrays (ie objects) and real arrays are entirely different types.
A claw hammer that occasionally bites your hand off is a bad claw hammer. (Bad! No biscuit!)
Its not proof the language is bad, its proof the poster is no better than the truly bad programmers who use the language he is trying to make fun of.
$bool = (08 === 0);
var_dump($bool);
This prints bool(true)
In other words, at the deepest level of identity this language can check, 08 is reported to be equal to 0.With a language like that, I think it's safe to blame the tool.
But no other language I've used would work this way. hash[8] would be the same as hash[010] and hash[0x8], and distinct from hash['8']. In addition, if anybody told you that strings would be interpreted as integers, you'd expect that octal strings (which PHP obviously understands) would be interpreted as integers as well! Instead, only decimal formats are handled.
This pernicious confusion of datatypes in the name of convenience is exactly what makes writing correct PHP code so infuriating.
If you want to put the blame entirely on "bad PHP developers", I have some datetime and object-equality behaviors to discuss.
Actually, while we're on the topic: these should be separate types, for exactly the reasons I outlined in that code snippet. Arrays and hashes have entirely different memory characteristics, access times, growth strategies, and indexing semantics! Trying to smush both models into the same construct is what leads to PHP's befucked implementation of "arrays"/"hashes", which succeed at being neither.
As an example, compare Ruby (an abysmally slow language) to PHP on array iteration--a task in which PHP loses by a huge margin on both memory and time complexity.
If you want to see what I mean, just try the framework I built for an hour. It's more "php-like" than the rails clones out there.
1) They don't extend stdClass so they aren't technically objects-- they're a different data type completely (WTF?) 2) Arrays are passed by value and not reference by default. Double WTF. So passing an array to a method call without the & reference operator is inefficient and prone to bugs as noobs don't expect the immutable behavior.
I think copy on write was added in the 5.1 timeframe (around 2005)
What's the difference between PHP's arrays and hashtables/dictionaries/etc in languages like Python, Ruby, and JavaScript?
As a Python programmer (who started with PHP years ago), PHP's arrays now seem sort of muddled or confusing. I prefer Python's dedicated list/dict types (though nothing is stopping you from mixing numeric and string keys in a dict).
I mean beauty in the sense of appreciating something. Just because your wife isn't a supermodel, doesn't mean you cannot find her beautiful and have a good marriage. Once you accept PHP for what it is, you find that there's a certain file-oriented style of coding that is perfectly suited to it, that embraces the unique type of PHP arrays, and that autoloads files when needed.
In PHP, you have an array that is basically associative, BUT which you can iterate in the same order that keys are added. This data structure is very unique and often lets you write less code, since you don't have to store the order separately. It also happens to map to JSON very well. Javascript has something like this too, except there is no guarantee that all browsers will implement properties in the same order, and many people on the internet complain about this sort of thing:
http://code.google.com/p/chromium/issues/detail?id=883
http://code.google.com/p/chromium/issues/detail?id=20144
I have to say, I feel for those guys.
http://ruby-doc.org/core/classes/Hash.html
"Hashes enumerate their values in the order that the corresponding keys were inserted."
Some languages have strengths for particular applications, but spaghetti can be written in anything.
And why should you care if 99% of the rest of the world writes shit code with the language you use, as long as your own house is clean?
Components like templating, views, active record, form validation, etc, are completely optional, and it's trivial to replace or extend components without having to mess around with any of the core code. Just don't load that component, and use something else instead.
--------------------------
Not to my knowledge ... there has been a rise in said lightweight frameworks, but thats just because heavy Frameworks like rails don't work for every scenario
Really? It took 5 major releases and 9 years?
Ruby and Python have been around as long or longer, but seemed to get the language basics/semantics down earlier. They also grew a lot slower compared to PHP.
If you don't want to admin Linux, for five lousy bucks a month asmallorange.com will set you up for Django (if it isn't already setup on the shared host) if you just ask nicely. They advertise Rails 2.3 support by default.
unless you had the nerve to already be an Amazon customer earlier.