Sunday, May 23, 2010

PHP essentials for Java programmers

I recently had to do a project in PHP and being from Java background one notices enumerable similarities. Obviously the whole knowledge about object-oriented programming and the procedural constructs like assignments, statements, conditions, loop etc are totally transferable. However the key difference I noticed was in the function calls. In Java all the arguments are passed by value, even for the objects, ie we pass the copy of the address for the object. But in PHP we are allowed to pass arguments by value or reference. Thus we have a simple function

function writeName($name) { echo $name; }

it passes the $name argument as value. However, by just prefixing $name with an ampersand we pass the argument by reference to give

function writeName(&$name) { echo $name; }

The other clever thing about PHP function is that we can return a value by reference too. Take the example from Joomla! library:


function &getLanguage()
{
static $instance;

if (!is_object($instance))
{
//get the debug configuration setting
$conf =& JFactory::getConfig();
$debug = $conf->getValue('config.debug_lang');

$instance = JFactory::_createLanguage();
$instance->setDebug($debug);
}

return $instance;
}

Preceding the getLanguage() function by an ampersand indicates that the function will return a value by reference, thus the return is a pointer to $instance.

The another line which will puzzle Java programmers above is

$conf =& JFactory::getConfig();

=& the syntax simply means that $conf is being assigned reference to the object created by getConfig() method of JFactory class. :: notation indicates that we are invoking a class method rather than an instance method. The normal Java dot notation of object.method() for invoking an instance method is changed in PHP to object->method()

Armed with the knowledge in this article a Java programmer is ready to do a PHP project. The only other thing to bear in mind is that the class constructor is defined by function __construct(). Obviously one will have to come to grips with various PHP functions but this should be no different from understanding a new Java API.