note 109405 modified in language.oop5.typehinting by danbrown
| From: | danbrown@php.net | Date: | Mon, 16 Jul 2012 15:17:44 +0000 |
| Subject: | note 109405 modified in language.oop5.typehinting by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189174@lists.php.net to get a copy of this message | ||
my scalar type hinting solution (example): <?php class
Scalar { /** * *
@var mixed */ private
$value; /** * *
@param mixed $v */ public function __construct($v)
{ $this->value = $v;
} /** * * @return
string */ public function __toString()
{ $v = strval($this->value); return
$v; } /**
* * @return bool */ public function
toBool() { $v = (bool) $this->value;
return $v; } /**
* * @return float */ public
function toFloat() { $v = floatval($this->value);
return $v; }
/** * * @return int
*/ public function toInt() { $v =
intval($this->value); return $v;
} /** * * @return
string */ public function toString() {
$v = strval($this->value); return $v;
} } class String extends
Scalar { /** * *
@param string $v */ public function __construct($v)
{ if (is_string($v)) {
parent::__construct($v); } else { throw new
InvalidArgumentException(); }
} /** * * @param
mixed $v * @return String */ public
static function parse($v) { $v = strval($v);
return new String($v);
} } /**
* * @param string $s */ function
myFunction($s) { new String($s); // now $s must be a string to
continue //... } ?>
--was--
my scalar type hinting solution (example):
<?php
class Scalar {
/**
*
* @var mixed
*/
private $value;
/**
*
* @param mixed $v
*/
public function __construct($v) {
$this->value = $v;
}
/**
*
* @return string
*/
public function __toString() {
$v = strval($this->value);
return $v;
}
/**
*
* @return bool
*/
public function toBool() {
$v = (bool) $this->value;
return $v;
}
/**
*
* @return float
*/
public function toFloat() {
$v = floatval($this->value);
return $v;
}
/**
*
* @return int
*/
public function toInt() {
$v = intval($this->value);
return $v;
}
/**
*
* @return string
*/
public function toString() {
$v = strval($this->value);
return $v;
}
}
class String extends Scalar {
/**
*
* @param string $v
*/
public function __construct($v) {
if (is_string($v)) {
parent::__construct($v);
} else {
throw new InvalidArgumentException();
}
}
/**
*
* @param mixed $v
* @return String
*/
public static function parse($v) {
$v = strval($v);
return new String($v);
}
}
/**
*
* @param string $s
*/
function myFunction($s) {
new String($s); // now $s must be a string to continue
...
}
Code could be found here:
https://code.google.com/p/myquicknet/source/browse/src/php_class/com/googlecode/myquicknet/scalar/
http://php.net/manual/en/language.oop5.typehinting.php