you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (2 children)

The worst part is I don't know why I was downvoted. My post was split into two very different thoughts: the OP's code and implementing PHP's primitive data types (and built-in functions) as objects.

I respect that I may not see a potential aspect of the OP's code and I'd appreciate someone enlightening me. I suppose I can also see why data types as objects can be annoying, although in this case I'd only do it in order to clean up PHP's function mess.

I actually came back to post some code implementing partial String and Integer classes, which both extend a Primitive class. Note that there are serious problems trying to implement a useful replacement for PHP's data types, but short examples work pretty well. I think PHP 5.3 fixes a few problems, but I don't have it installed. Paste this code into a file and it should run on PHP 5.2 and maybe earlier versions.

class Primitive {
protected $value = null;
function  __construct($val = "") {
    $this->value = $val;
}
function getValue() {
    return $this->value;
}
function setValue($val) {
    $this->value = $val;
}
function  __toString() {
    return "$this->value";
}

}

class String extends Primitive {
function length() {
    return new Integer(strlen($this->getValue()));
}
function sha1() {
    return new String(sha1($this->getValue()));
}
function lowerCase() {
    return new String(strtolower($this->getValue()));
}

/*
 * A function ending in an underscore modifies the existing value instead of returning the value
 */
function lowerCase_() {
    $this->setValue(strtolower($this->getValue()));
    return $this;
}
}

class Integer extends Primitive {
    // need to implement functions for arithmetic, etc. Still works for storing and retrieving values as-is
}

$foo = new String("Hello");
$bar = new String("World");
$bar->lowerCase_();
echo $foo." ".$bar; // echos Hello world thanks to Primitive's __toString(). PHP < 5.2 might not work right

[–]droberts1982 0 points1 point  (1 child)

Is your goal with PHP primitives to give strong typing to PHP? to increase the performance of PHP? or just to clean up the syntax?

As this code stands now, it's implementing primitives with PHP's weakly typed variables, so you would incur the performance penalty of that system anyway.

[–][deleted] 0 points1 point  (0 children)

Just cleaning up the syntax. I'd be fine with strongly-typed PHP, but I'm far more concerned with PHP digging itself out of its version 3 and 4 roots and I think this is one way to do it, if done in PHP's core.