Python vs. PHP

Introduction

Every month or so someone posts to comp.lang.python asking how Python compares to PHP. Python's 'language comparisons' page doesn't have an entry for PHP so here's a first draft. This work-in-progress compares PHP and Python and evaluates their relative strengths for web development.

Please contribute! Once there's some flesh on this skeleton, I'll tidy it up and submit it to: http://python.org/doc/Comparisons.html

-- TavisRudd - 23 Nov 2001 -- MikeOrr - 15 Dec 2001 -- DiogoResende - 21 Jun 2007 :) -- SamuelCochran - 6 Jan 2008 -- Pomax - 23 Jan 2010

Common Ground

Both PHP and Python:

Compared as Languages

What does PHP have that Python doesn't?

  • syntactic scoping (using curly braces)

  • variable syntax (dollar signs indiciate variables)

  • 'switch/case' statement and 'do ... while' construct

  • increment and decrement and assignment operators (assignment is a statement only in Python)

  • the ternary conditional operator (... ? ... : ...)

  • script-global variable protection (script-global variables must be imported by a function before they can be used)

  • class-global variable protection (class-global variables must be indicated as $this->varname, $varname variables are local scope)

  • primitive variable declaration-on-initialisation: a primitive variable (including array) does not need to be explicitly declared. when an assignment involved a variable that does not exist, it is created on the fy.

  • an expedient (commonly installed) environment

  • references - in assignment such as '$a =& $b', $a becomes an alias for $b (modifying the data via $a is functionally equivalent to modifying the data via $b).

  • single primitive for arrays and maps - the 'array' primitive is actually a map which will can either map incremental numbers to data (acting as an array) or map explicit keys to data (action as a hash, dictionary, or whatever other name you know maps as)

  • excellent on-line manual with registration-less user contributions to further explain functions and their use "in the wild"

  • object level functions. Where in python all class-defined functions are class function, and must be passed a 'self' argument in order to operate on an instantiaed objects, in php all-class defined functions are object functions unless explicitly marked static.

What does Python have that PHP doesn't?

  • scoping based on indentation level (rather than relying on curly braces to indicate scope)

  • namespaces and modules

  • supports self-documenting code (via docstrings and pydoc)

  • keyword arguments to functions and methods

  • everything is an object (there are no primitives)

  • multiple inheritance

  • object-oriented file handling

  • built in reflection

  • everything is pass-by-reference

  • consistent case sensitivity (PHP is case-sensitive for variable names, but not for function names)

  • true lambdas and other builtin functional programming constructs

  • operator overloading

  • SWIG integration

  • threading

  • many predefined common high-level data types (lists, tuples, dictionaries, datetimes, arrays, etc.)

  • distinction between enumerated lists (arrays) and and maps (associative arrays)

  • builtin concept of date that doesn't rely on computation involving the UNIX epoch (dates can go <1970, >2038)

  • strong internationalization

  • strings work with all unicode 5.1 characters (php only supports multi-byte strings via an extension, which does not offer all the operations that exist for normal strings)

  • module importing (php relies on code inclusion instead)

  • uniform function naming (PHP's built-in library does not stick to a single naming convention)

  • (support for all major GUI frameworks -- a list is missing, so until someone specifies what they consider major, this is a moot point)

  • (maturity, stability and upward-compatibility -- PHP is stable and mature [but not clean] and python 2.6 is not compatible with 3.x [and presumably every version after that], so this point is fairly useless)

  • (a small core -- but small for what purpose? PHP's 5Mb is small if used on servers or workstations, but big if it needs to be embedded, so this again looks like a moot argument unless a context is stated)

Compared as Web Development Frameworks

Unlike PHP, which has web development features built directly into the core language, Python's web development capabilites are provided by add-on modules. Basic CGI capabilities are provided by the 'cgi' module which comes in Python's standard library. There's also a wide range of third-party modules available for Python; some are complementary, others compete. As a result, Python provides a more flexible base for web development.

There are some adverse side effects of this flexibility. First, the range of choices can be bewildering. Unless you are working experienced Python web developers, PHP is easier to get started with. Second, support for PHP is more common with shared-hosting companies than support for the various Python options.

Another difference is that PHP is embedded in the web server, whereas Python web applications can either be embedded in the web server like PHP or run in a separate process. Here's a simple classification of Python web development platforms:

  • emdedded in the web server process

    • Apache modules mod_python and mod_snake embed the Python interpreter in Apache and allow other Apache modules to be written with Python. This is the same idea as mod_perl.

    • PyWX is an extension to AOLServer that serves the same purpose as the Apache modules above.

    • MS ASP scripts can be written using Python via Active Scripting Host.

  • running in a separate process

    • non-persistent process (a new process is spawned for each request)

      • custom CGI scripts

    • persistent process (all requests are sent from the web server to one persistent process, sometimes via a CGI wrapper)

      • custom Fast-CGI scripts

      • custom SCGI scripts

      • custom WSGI modules

      • 'Application Servers'

        • Zope -- comes with its own web server but can also communicate with Apache via the CGI or Fast-CGI protocols.

        • Webware -- works with any web server via CGI. With Apache it can communicate via a custom Fast-CGI like protocol.

        • SkunkWeb -- only works with Apache, communicates via a custom Fast-CGI like protocol.

(Note: PHP programs can be run standalone or as ordinary CGI scripts. However, when called indirectly from the web (e.g., from a Perl CGI script), it requires unsetting an undocumented number of web environment variables so that PHP doesn't think it's running from the web and look in the wrong place for the script. Likewise, it's _possible_ to write a long-running server in PHP, but there are precious few examples of it.)

The vast majority of Python web applications are run in a separate process. This has some important implications. ... to be continued ...

... please add your observations

Python Application Servers

...

Python Template Engines

...

Here's some interesting notes on security in PHP: (Not true. The tutorial assumes default conf values that are not default anymore or don't even exist) http://www.securereality.com.au/studyinscarlet.txt

Community Support

PHP

  • huge installed user base, but the figures are probably distorted by shared hosting (Not true. It has PEAR and PECL repository)

  • low signal-to-noise ratio -- because PHP is so expedient, many of the users are not invested in the technology (or even their own code) or the community (Not true. IBM and Oracle invested in PHP)

Python

  • sizable, but not huge, installed user base

  • Python Software Foundation

  • lots of specialized interest groups

  • very high signal-to-noise ratio

Documentation

Core Documentation

Although both PHP and Python have excellent core documentation, Python's is more extensive and generally higher quality. PHP has a large number of translations available. Python doesn't. For PHP see http://www.php.net/docs.php and for Python see http://python.org/doc/ Python allows documentation on modules, classes, and functions to be included in the program code. The documentation becomes an attribute of the module/class/function, accessible from inside of the language itself. (This is so untrue. Python docs are short and don't explain in detail how something can or should be used. PHP uses examples (L.B.E.). PHP has comments on every page so you can check for someone that tried to do the same thing you did. PHP can be documented just like many other languages like C for example; http://www.phpdoc.org/ )

Conclusion

it is not up to the rest of us to tell you which programming language to favour. Learn both, and learn which to use when. If you find out you end up using PHP or Python more than the other, then you know which programming language works best for you. If the job you need to get done relies on specific features that are available to one, but not the other, then there is no choice to make, go with the one that offers this feature.

Frequently Asked Questions

Q1

... what is the best way to build web-based database applications like accounting systems, on Python? i.e. what is the equivalent of ASP pages or PHP pages or JSP pages, for Python?? Shouldn't we be learning THAT instead of PHP???

A1

There is no simple answer to this question. There are many tools available for doing this in Python. So many that the choices can be bewildering. You're best to think of the tools as falling into two complementary categories: Application Servers (there's probably a better term to use here) and Template Engines.

Application Servers:

Templating Engines:

My personal preference is Apache/Webware/Cheetah. I'll write more about this later. -- TavisRudd - 23 Nov 2001

General Discussion

(add your comments here, along with a signature and date)


I haven't used PHP with XML, and I've only used Python with XML a little, but I get the impression Python is much better suited -- specifically because it is strongly types, where PHP is rather weak in its typing (like C). But I can't say from experience

-- IanBicking - 26 Nov 2001


To clarify, PHP's types are more dynamic than Python's. All variables are automatically initialized to NULL. It automatically converts between strings, numbers and NULL when a different type is needed for the operation, or with a type case. It also "does something" to convert to/from array and object. '123' -> 123, 'non-numeric' -> 0, NULL -> '', etc. Sometimes all this is convenient, especially when a missing CGI param converts to NULL which converts to '' in the VALUE= attribute, but it also leads to wrong ouput rather than errors if you misspell a variable or key.

PHP does not have first-class functions. There are equivalents to Python's map, reduce, filter, and there's array_walk, but they all take the name of a function rather than the function itself.

Examples of PHP's schizophrenic function naming: (string functions) stripslashes vs strip_tags; (array functions) array_keys vs asort vs count and shuffle; (variable functions etc) isset vs is_array.

PHP has constants, which are initialized with a totally different syntax than variable assignment. The advantage of constants is that they can be defined only once, allowing you to define sensitive constants in a secure include file, then prevent untrusted code from overriding them. Constants are global: they bypass the scoping rules. One disadvantage is that a constant is a bare word: if you misspell it, you'll silently get a NULL value.

Syntax errors show the file and line number, but not the character position. Sometimes the error message is specific, sometimes just "parse error". This leads to staring at the code for a while until you realize you're missing '$' or ';', or you put something besides a semicolon on the END line matching <<<END .

-- MikeOrr - 15 Dec 2001

This document has become rather old. With PHP 5.2.x and Python 3.0 out, and almost 10 years after this document was first drafted, it has become clear that, from the perspective of a person who intends to use these languages, the choice between them is essentially arbitrary. For trivial tasks it is irrelevant which is being used (because then it's not a choice between PHP or Python, but between every programming language for which there are compilers and interpreters available), and for complex tasks more often than not someone has already done what you need in both PHP and Python, as well as typically in Perl and Ruby.

Also, do not be taken in by trivial differences: Python's indented scoping vs. PHP's explicit scoping is only syntactic sugar: the transformation from one method of scoping to the other is the most basic of trivial transformations, and if you want you can set up your interpreter so that it always runs your script through that transformation before executing, so you can code PHP with indentation scoping, or Python with curly braces.

Python's use of module imports rather than PHP's code inclusion is a strong argument to use Python in structured complex situations, but careful programming and using project-specific conventions (and sticking to them) will achieve the same in a PHP project (although you won't find a single experienced programmer out there who will not tell you that modules and packages are a cleaner, and easier to debug approach).

With IDEs such as Eclipse offering plugins do PHP as well as Python development, the IDE availability argument is also moot. As ever, the conclusion must necessarily be: use the language that gets the job done best, in the least amount of time, with the least amount of debugging. Everything PHP can do, Python can do, and vice versa; you want to select your language based on how they behave when things don't work. Is it easier to debug a PHP application or a Python application? No one knows, actually, because a well designed application doesn't break, and a poorly designed application is as poor as the programmer's oversight.

-- Pomax - 2010/01/23