note 103457 deleted from intro.spl-types by danbrown
| From: | danbrown@php.net | Date: | Thu, 14 Apr 2011 14:58:16 +0000 |
| Subject: | note 103457 deleted from intro.spl-types by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178837@lists.php.net to get a copy of this message | ||
Note Submitter: aargoth at boo dot pl
----
Please note, there is a fully implemented strong typing in PHP.
It's fully described in this article: http://php.webtutor.pl/?p=810
How does it work? You have to import one PHP library to your existing projects, and create some
classes, in which the scalar values will be automatically wrapped by an autoboxing mechanism known
from Java, like so:
class String extends AutoBoxedObject
{
public $value;
public function __construct($value) {
$this->value = $value;
}
public function __toString() {
return "$this->value";
}
public function toUpperCase() {
return strtoupper($this->value);
}
}
function & string($value = null) {
$x = & VariablesManager::getNewPointer(new String($value));
return $x;
}
From now on you can declare the type of data in your variables, and validate their values, if they
are correct:
$y = & string("aaa");
// lets check, that $y is an object
var_dump($y);
// now we are overwritting $y variable with a scalar value of "zzz"
$y = "zzz";
// var_dump() shows us, that "zzz" is still an object, not the scalar type as in regular
PHP
var_dump($y);
// the line below should raise a fatal error, because "zzz" was a scalar type (string),
but it will be ok, because $y is still an object (thanks to autoboxing)
var_dump($y->toUpperCase());
Now, the output is:
object(String)#1 (2) {
["value"]=>
string(3) "aaa"
["ref":protected]=>
int(1)
}
object(String)#2 (2) {
["value"]=>
string(3) "zzz"
["ref":protected]=>
int(1)
}
string(3) "ZZZ"
As you can see, PHP can be as good as Java or C#:)