PHP lacks true object comparability
For those of you who read the f* manual and see that section called object-comparison. You already realize that its a misnomer or you might be oblivious to another reason why objects in PHP are still second, even third class citizens.
Currently I’m writing a moderate set of Types for Midori-Php (granted i have most of it already written, i’m going back and for the first ctp just releasing the core types, which means i need to document, test, and test some mo). And for those of you that think this is a crazy idea, welp the PHP internals have started to do the same things themselves…. just lacking documentation and anything really useful at the moment. This just adds to why PHP feels like the IE of programming languages and a complete blight.
I think its sad that PHP 5.3 is currently at RC2 as I write this post and the only thing you can really check with object is equality using ==. You can not use operators like greater than (>), less than(<), etc on objects in PHP. The code below will illustrate php’s lack of true object comparison. Though I won’t say this takes away from the whole notion that PHP is enterprise ready, it does take away from the ease of use of objects in PHP and thus could take away from its maintainability.
class Midori_Int32
{
public $value = 0;
public function __construct($value = 0)
{
$this->$value = $value;
}
}
$a = new Midori_Int32(45);
$b = new Midori_Int32(10);
//this would be legal, for shallow checking use ==, use === for deep comparisons
$condition = ($a== $b)
// this is illegal in php
$condition2 = ($a >= $b);
In Ruby (where everything is an object) they allow for operator overloading on method so you can define custom object types with comparability.
class MidoriInt32
def initialize(value)
@value = value
end
def === (obj)
return @value === obj
end
def > (obj)
return @value > obj
end
end
a = MidoriInt32.new(3)
b = MidoriInt32.new(4)
condition = (a === b)
condition = (a > b)
though it may be unknown, you can do the same in dot .net using IComparable. If you need to override things like math operators or type conversion you need to check out the wicked cool operator keyword
using System;
public class MidoriInt32 : IComparable
{
public MidoriInt32(int value)
{
this.Value = value;
}
public int Value { get; set; }
public static MidoriInt32 operator +(MidoriInt32 objA, int objB)
{
return new MidoriInt32(objA.Value + objB);
}
public static MidoriInt32 operator +(MidoriInt32 objA, MidoriInt32 objB)
{
return new MidoriInt32(objA.Value + objB.Value);
}
public int CompareTo(object obj) {
{
if(obj is int)
return this.Value.CompareTo(obj);
else
throw new ArgumentException("Object is not an integer");
}
}
// test
class TestStuff
{
public void Test()
{
var a = new MidoriInt32(3);
var b = new MidoriInt32(4);
var condition = (a > b);
var condition2 = (a === b);
}
}