Article

PHP & C

August 21, 2009 | Posted by Cody


For those familiar with C, PHP seems strikingly similar. From the syntax to the function calls. It’s almost as if you could replace a couple asterisks (*) with dollar signs ($) and add a PHP-tag or two, and you could run your C source raw.

#include <stdio.h>
 
main() {
	char *phrase = hello world!n;
	printf(%s, phrase);
}
<?php
function main() {
	$phrase = “hello world!n”;
	printf(%s”, $phrase);
}
?>

The Big Blue C In recent time PHP has diverged from C’s familiar convention, in an attempt to offer a higher level experience. Much of this relates to IO. For example, PHP 4 required you to call fopen, then fwrite, and finally fclose in order to write content to a file, just as you would do in C. In PHP 5 file_put_contents was added in, which operates more of how you would expect from a scripting language. Although much has changed, some things likely never will. For example, command line parameters are handled in just about the same way. And while I haven’t viewed the source, I suspect fgetc directly invokes the C library. In fact, just about every function in the standard IO library (stdio.h) in ANSI C is represented in PHP. Static, Extern and Global PHP and C handle static variables within functions in exactly the same way. However, since PHP refuses to search the call stack outside of a function’s scope, a global keyword is required to pull these variables into scope so they can be used within a function. While this works similar to C’s extern declaration, unlike in C, you can’t ever use a variable defined outside a function, even if declared before the function, unless it is declared global or is one of the special “super global” types. C You Later PHP never had pointers, though they do offer references similar to Java. The difference being that a reference can’t be moved or reassigned as a pointer can using pointer arithmetic. PHP 5 raises errors when attempting to pass references to functions. While it’s still possible to pass by reference, the function or method signature must define it and the call must not include the ampersand (&). This is because, as of PHP 5, non-primitive types are implicitly passed by reference. While in some respects PHP has moved away from its C influence, in other aspects it’s become more similar. PHP 4, for example, added capabilities for variable length parameters, although in a much different way than C. Nevertheless, the C influence appears to be dwindling, in favor of higher level capabilities, such as XML parsing, and simpler IO. So it’s unlikely we’ll see new primitive C constructs, such as goto’s any time soon… or will we?

Tags: