note 103463 deleted from language.oop5.typehinting by cmb
| From: | cmb@php.net | Date: | Sat, 10 Dec 2016 11:44:27 +0000 |
| Subject: | note 103463 deleted from language.oop5.typehinting by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208440@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
Please note, there is a strong typing in PHP.
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:
<?php
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 in a class
constructor.
See this example:
<?php
$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#:)
To enforce strong data types you just have to do it in the wrapper class, like so:
<?php
class Integer extends AutoBoxedObject
{
public $value;
public function __construct($value) {
if(!is_int($value)) { throw new Exception("Invalid data type"); }
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function __toString() {
return (string)$this->value;
}
}
?>
To download the library, just google for 'strong data typing autoboxing' . There is an
article describing how to use it, and a download link to the appropriate PHP library.