Advertisement
Guest User

Untitled

a guest
Nov 17th, 2013
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.72 KB | None | 0 0
  1. <?php
  2.  
  3. class MyString{
  4.     function __construct($string){
  5.         $this->storage = $string;
  6.     }
  7.     function substr($from,$len){
  8.         return new static(substr($this->storage, $from, $len));
  9.     }
  10.     static function __fromScalar($value){
  11.         return new static($value);
  12.     }
  13. }
  14.  
  15. function test(MyString $value){
  16.     echo $value->substr(0,5);
  17. }
  18.  
  19. test("hello world"); // implicitly constructs the object via MyString::__fromScalar() and prints "hello"
  20.  
  21. // ---------------------------------------------------------------------
  22.  
  23. class Color
  24. {
  25.     function __construct($red, $green, $blue, Integer $alpha = 1){
  26.         // ...
  27.     }
  28.     static function newFromHex(String $string){
  29.         // ...
  30.     }
  31.     static function newFromHSV(...){
  32.         // ...
  33.     }
  34.     static function newFromHSL(...){
  35.         // ...
  36.     }
  37.     static function __fromScalar($value){
  38.         if(preg_match("@^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$@i", $value))
  39.             return static::newFromHex($value);
  40.         elseif(preg_match(...))
  41.             return static::newFromHSL(.....);
  42.         elseif(preg_match(...))
  43.             return static::newFromHSV(.....);
  44.         // ...
  45.         else
  46.             throw new Exception("couldn't parse the color string");
  47.     }
  48.     function setAlpha(Integer $alpha){
  49.         $this->alpha = $alpha;
  50.     }
  51.     function __toString(){
  52.         // ...
  53.     }
  54. }
  55.  
  56. function test(Color $color){
  57.     return $color->setAlpha(0.9);
  58. }
  59.  
  60. test("#ff0000"); // prints rgba(255,0,0,0.9)
  61. test("rgb(255,0,0)"); // prints rgba(255,0,0,0.9)
  62.  
  63.  
  64. // ---------------------------------------------------------------------
  65.  
  66. // also:
  67.  
  68. // method return type:
  69. function ReturnTypeClass test(String $test){
  70.     return "hello"; // correct, equals to write "return ReturnTypeClass::__fromScalar("hello");"
  71. }
  72.  
  73. class ReturnTypeClass{
  74.     static function __fromScalar($value){
  75.         return new self($value);
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement