DulcetAirman

php: addCharsAt

Apr 9th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. class Foo {
  3.     public $string = '';
  4.     //public $length = 0;
  5.  
  6.     public function __get (string $name) {
  7.         if($name === 'length') return strlen($this->string);
  8.         $trace = debug_backtrace();
  9.         trigger_error(
  10.             'Undefined property via __get(): ' . $name .
  11.             ' in ' . $trace[0]['file'] .
  12.             ' on line ' . $trace[0]['line'],
  13.             E_USER_NOTICE);
  14.         return null;
  15.     }
  16.    
  17.     public function __isset ( string $name ) : bool {
  18.         if($name === 'length') return true;
  19.         return false;
  20.     }
  21.  
  22.     public function __debugInfo() : array {
  23.         return [
  24.             'length' => $this->length,
  25.             'string' => $this->string
  26.         ];
  27.     }
  28.  
  29.  
  30.  
  31.     public function addCharsAt(int $index, string $chars) {
  32.         if(strlen($chars) === 0 || $index < 0 || $index > 1 + $this->length) return null;
  33.         $str='';
  34.         $len = $this->length;
  35.         for ($i = 0; $i <= $len;) {
  36.             if ($i === $index) {
  37.                 $str .= $chars;
  38.                 $index = -1;
  39.                 //$this->length += strlen($chars);
  40.             } elseif ($i < $len) {
  41.                $str .= $this->string[$i];
  42.                $i++;
  43.             } else break;
  44.         }
  45.         $this->string=$str;
  46.         return null;
  47.     }
  48.  
  49.  
  50. }
  51.  
  52.  
  53. $foo = new Foo();
  54.  
  55.  
  56. $foo->addCharsAt(0, "test");
  57. var_dump($foo);
  58.  
  59. $foo->addCharsAt(2, "xx");
  60. var_dump($foo);
  61.  
  62. $foo->addCharsAt(6, "yy");
  63. var_dump($foo);
Add Comment
Please, Sign In to add comment