Wrapping C++ Classes in a PHP Extension

I have a tutorial at the Zend Developer Zone called Wrapping C++ Classes in a PHP Extension. It walks you through writing a simple PHP extension that wraps a class written in C++. This is a useful thing to be able to do, especially when exposing an already existing library’s API to PHP userland scripts, which seems like a fairly common task.

Bad Signs – PHP’s “Shut Up” (@) Operator

Derick Rethans has a post about PHP’s “shut-up” operator (@) and why it should be avoided. He outlines a fairly common debugging scenario and gives some “under-the-hood” explanations on why that particular operator sucks. I couldn’t agree more (that it should be avoided) and I want to go further and talk about something that has always bugged me about that operator. In my opinion, it’s a hackish, band-aid fix to a much larger, much more worrisome problem: horrendous API design.

First, a disclaimer. I know that there are some historical reasons for a lot of these things (i.e. Exceptions not appearing until PHP5) but that doesn’t change the current reality. Consider for instance filesystem functions in the standard extension:

$lines = file("/tmp/file.txt");

If the file “/tmp/file.txt” does not exist, depending on your php.ini settings (because display_errors should always be ‘Off’ on production systems), you may get something similar to the following output:

Warning: file(/tmp/file.txt) [function.file]: failed to open stream: No such file or directory in /path/to/your/docroot/test.php on line 3

Now the proper thing to do of course would be to verify up front that the file exists and is readable with a call to is_readable() or something similar, but imagine this is a case where there is no way to determine ahead of time if a warning or error will be generated (Derick mentions silencing network errors with stream_socket_client() as one example). In this case, you might be tempted to use the shut-up operator and depend on the return value as the one true way to see if something was succesful or not.

Now compare this with what languages like Python (for example) do, If you were to write similar code in Python:

fp = file("/tmp/file.txt")

If the file did not exist, you’ll get an IOError which, if left uncaught, will result in the following being written to standard error:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
IOError: [Errno 2] No such file or directory: '/tmp/test.txt'

The difference here of course is that an IOError can be caught, ignored or whatever best suits your needs. It’s a part of the language, the API is not just spewing out garbage to standard output or standard error. More importantly, having a function (or technically a constructor) like file() throw an exception follows a consistent design philosophy whereas PHP’s error system always leaves me guessing or consulting the docs.

I guess what I’m saying is that I think the shut-up operator is just one of those signs that PHP is suffering from some serious cruft and I don’t think those kinds of things bode well for a language.

What drove me away from Apple

I recently replaced my Macbook Pro with a Thinkpad x200 running Arch Linux and Windows Vista. After 5 years of using Apple products I decided to switch – to borrow one of their marketing terms – because frankly, I was sick of being abused as a customer and the lock-in was making me less and less comfortable. Here’s a list of the things that really did it for me:

  • Pricing the Macbook Air so high with such low specs.
  • Releasing an pitiful update to the air along with a nice $100 price increase.
  • Doing away with the matte screen option.
  • Pulling the remotes from being included with laptops (admittedly not a huge deal, but felt like salt on a wound).

Is it just me or is Apple becoming a little too arrogant? Anyway, I know Lenovo won’t be saints either, but at least in the non-Mac OS X world I can easily switch vendors down the road if I ever need to.

PHP is Lazy

Last week I started reading Extending and Embedding PHP. I really like extending scripting languages for a number of reasons, most of all because it’s a great way to learn about the more esoteric features of a language. So far I’ve discovered two neat things about PHP that made me smile, so I thought I’d share them here.

Copy on Write

In an effort to save CPU cycles, PHP uses an optimization strategy called “Copy on Write”. Basically what this means is that variable data isn’t copied until it needs to be. Using an example similar to the one found in the book:

$a = 50;
$b = $a;
$b += 5;

At the first line, the variable $a is created and memory is allocated for it. When we set $b to equal $a however, you might think that the data in $a is copied to $b. PHP doesn’t actually copy the data until the 3rd line when $b is incremented by 5. The value in this is that data is not copied unnecessarily. If, for some reason, we took out the 3rd line and $b was never modified after the initial assignment, the data would actually never have to be copied.

Return Value Used?

The second, admittedly more surprising thing I learned was that PHP provides internal functions a parameter called return_value_used whose value can be inspected to determine whether the return value being prepared by the function is actually being saved or not. Imagine you have a function that does some heavy crunching to compute a return value, and a caller (for some reason beyond us) does this:

<?php
...
myextension_compute_something();
...
?>

In other words, they call the function but don’t store the return value. Well, being a thoughtful internal function author, you can check to see that return_value_used evaluates to false and just skip doing any work, saving CPU cycles and time, like so:

PHP_FUNCTION(myextension_compute_something)
{
    if (return_value_used) {
        // some fancy but expensive algorithm
        // ...
        RETURN_DOUBLE(some_value);
    } else {
        RETURN_NULL();
    }
}

ZendCon 2008 – Day 2

Harold Goldberg, the CEO of Zend Technologies, started the day off with a talk called “Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP Applications”. The talk was basically a run-down of how PHP is doing out there. (Answer: Fairly well!). There were a few case studies of larger companies using PHP (and of course Zend products) and a few reports / surveys / etc. Nothing particularly groundbreaking but it was good to start the day feeling pumped about being a PHP programmer…

Later on I attended “Tiery-Eyed”, a talk given by a Zend employee, Kevin Schroeder on … you guessed it, tiered application development. It was pretty decent, Kevin walked the audience through the creation of a micro-blogging application using a variety of different backend tiers. I left with an urge to create the smallest application I could think off with one SOAP backend, one XML-RPC backend and one REST backend.

The highlight of the day was Sara Goleman’s talk on PHP Extension Writing. This was the most in-depth of the talks I attended and despite a few technical problems, the talk went smoothly. It was pretty broad but still managed to be quite inspiring.

The day ended with a reception in the exhibit hall. Free drinks and food is never a bad way to end a day…