SHOW:
|
|
- or go back to the newest paste.
| 1 | - | public function addCharsAt(int $index,string $char){
|
| 1 | + | <?php |
| 2 | class Foo {
| |
| 3 | - | $is_added=FALSE; |
| 3 | + | public $string = ''; |
| 4 | - | for ($i=0;$i<$this->length;$i++) {
|
| 4 | + | //public $length = 0; |
| 5 | - | if (!$is_added&&$i == $index) {
|
| 5 | + | |
| 6 | - | $str .= $char; |
| 6 | + | public function __get (string $name) {
|
| 7 | - | $is_added=TRUE; |
| 7 | + | if($name === 'length') return strlen($this->string); |
| 8 | - | $i--;//go back one step. |
| 8 | + | $trace = debug_backtrace(); |
| 9 | - | } |
| 9 | + | trigger_error( |
| 10 | - | else |
| 10 | + | 'Undefined property via __get(): ' . $name . |
| 11 | - | $str.=$this->string[$i]; |
| 11 | + | ' in ' . $trace[0]['file'] . |
| 12 | ' on line ' . $trace[0]['line'], | |
| 13 | - | $this->string=&$str; |
| 13 | + | E_USER_NOTICE); |
| 14 | - | $this->length++; |
| 14 | + | return null; |
| 15 | - | } |
| 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); |