Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @name Custom casting helper
- * @author [email protected]
- * @internal
- */
- interface Castable {
- static function cast($var);
- }
- /**
- * @example hard casting (validation)
- */
- class ValidatedPositiveInteger implements Castable {
- static function cast($var) {
- if(!is_int($var)) {
- throw new InvalidArgumentException('Value is not an integer');
- }
- if($var < 1) {
- throw new InvalidArgumentException('Integer is not positive');
- }
- return $var;
- }
- }
- /**
- * @example soft casting (sanitization)
- */
- class SanitizedPositiveInteger implements Castable {
- static function cast($var) {
- $var = (int)$var;
- if($var < 1) $var = 1;
- return $var;
- }
- }
- // usage:
- $var = (ClassName)$var;
- function foo(ClassName $var) {}
- // in both cases will run under the hood:
- if($var instanceof Castable) $var = ClassName::cast($var);
- else { /*current behavior*/ }
- // usable cases:
- // 1. custom types with internal logic
- // 2. sanitization and validation of input
- // 3. casting from array to object (e.g. json, db row, etc.)
- // 4. casting from stdClass to object
- // 5. custom type juggling
- // 6. custom context dependent serialization/unserialization
Advertisement
Add Comment
Please, Sign In to add comment