May 13, 2009 4

PHP vs Python vs Ruby – OOP style syntax

By admin in php

Without a doubt the Ruby and Python snippets are more aesthetically pleasing to the eye and although they look almost the same for the untrained eye, the approach is fundamentally different.
This is the example class using PHP

class Species {
	private $_type;
	private $_name;
 
	public function __construct($type, $name) {
		$this->_type = $type;
		$this->_name = $name;
	}
 
	public function __get($fieldName) {
		switch ($fieldName) {
	      case "type":
	        return $this->_type;
	      case "name":
	        return $this->_name;
	      default:
	        throw new Exception("Attempted to access invalid property: ".$fieldName);
	    }
	}
}
 
class Human extends Species
{
 
	public function getLegs() {
		return 2;
	}
}
 
 
$person1 = new Human('Neanderthal', 'Reinhold Weber');
echo $person1->name;
echo ' has '.$person1->getLegs().' legs.';

The same using Python’s elegant syntax

class Species:
	def __init__(self, type, name):
		self.__type = type
		self.__name = name
	def get_name(self):
		return self.__name
 
class Human(Species):
	def get_legs(self):
	  return 2
 
person1 = Human("Neanderthal", "Reinhold Weber")
print person1.get_name()
print ' has ' + str(person1.get_legs()) + ' legs.'

Ruby, which seems almost the same as the Python snippet

class Species
  attr_accessor :type, :name  
  def initialize(type, name)
    @type = type
    @name = name
  end
end
 
class Human < Species
  def getLegs
    return 2
  end
end
 
person1 = Human.new 'Neandethal', 'Reinhold Weber'
print person1.name
print " has #{person1.getLegs} legs."

Tags: , , ,

4 Responses to “PHP vs Python vs Ruby – OOP style syntax”

  1. rahul says:

    I personally felt that ruby code offers more readability than python or PHP

  2. Chris says:

    Nah, the PHP syntax is much more elegant – mainly because it uses braces to encapsulate things. The python code has no end to each statement block and ruby used “end” – horrible, IMO!!!!

    Although, I’m not sure why you’ve over-complicated the PHP syntax with a switch in a magic __get() method, yet you’ve only used a get_name method in python and in ruby I’m guessing the properties are public – an approach you could have taken in the php example

  3. Calce says:

    Ruby’s “end” looks more elegant than braces to me

  4. Kevin says:

    Indeed. You have spaced the PHP code out so as to ‘maximise’ the messiness?

    I find PHP more easily readible.

Leave a Reply

Comment Spam Protection by WP-SpamFree