note 94310 modified in intro.spl-types by danbrown
| From: | danbrown@php.net | Date: | Wed, 28 Oct 2009 16:20:03 +0000 |
| Subject: | note 94310 modified in intro.spl-types by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162193@lists.php.net to get a copy of this message | ||
For backwards compatibility issues:
We do know that auto-unboxing works for strings, thanks to the __toString() magic function.
Auto-unboxing for other scalar types may be tricky but possible, by using the same function with
another return type (which of cause has some limitations).
However auto-boxing is a real challenge.
If you can provide any details, I would appreciate that.
For auto-unboxing see this code-fragment:
<?php
class MyString {
private $value = "";
public function __construct($string) {
if (!is_string($string)) {
throw new InvalidArgumentException();
}
$this->value = $string;
}
public function __toString() {
return $this->value;
}
}
?>
For other scalar types, all that changes is the constructor function. Anything else remains
unchanged. (While you are at it, you may want to add some type conversion functions for your
personal convenience.)
HowTo:
<?php
function foo(MyString $string)
{
print "$string"; // auto-unboxing in action
}
// prints "Hello World!"
foo(new MyString("Hello World!"));
?>
--was--
For backwards compatibility issues:
We do know that auto-unboxing works for strings, thanks to the __toString() magic function.
Auto-unboxing for other scalar types may be tricky but possible, by using the same function with
another return type (which of cause has some limitations).
However auto-boxing is a real challenge.
If you can provide any details, I would appreciate that.
For auto-unboxing see this code-fragment:
class MyString {
private $value = "";
public function __construct($string) {
if (!is_string($string)) {
throw new InvalidArgumentException();
}
$this->value = $string;
}
public function __toString() {
return $this->value;
}
}
For other scalar types, all that changes is the constructor function. Anything else remains
unchanged. (While you are at it, you may want to add some type conversion functions for your
personal convenience.)
HowTo:
function foo(MyString $string)
{
print "$string"; // auto-unboxing in action
}
// prints "Hello World!"
foo(new MyString("Hello World!"));
http://php.net/manual/en/intro.spl-types.php