Last active
December 12, 2022 12:32
-
-
Save gggeek/fda6e3a4d3bc52652859e8c7e9849996 to your computer and use it in GitHub Desktop.
playing around with emulation of array dynamic properties using __get, __set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyClass | |
{ | |
protected $p = array(); | |
public function &__get($name) | |
{ | |
echo "Getting: $name\n"; | |
if (!isset($this->p[$name])) { | |
// normally one would trigger a warning here, but this line is called by code doing point-blank `$obj->prop[] = $thing;` | |
$this->p[$name] = array(); | |
} | |
return $this->p[$name]; | |
} | |
public function __set($name, $value) | |
{ | |
echo "Setting $name to: "; var_dump($value); | |
$this->p[$name] = $value; | |
} | |
} | |
$c = new MyClass(); | |
$c->plain = 1; | |
$c->magic[] = 1; | |
$c->magic[] = array(2); | |
$c->magic[0] = 2; | |
var_dump($c->plain); | |
var_dump($c->magic); | |
$c->other = array(); | |
$c->other[] = 1; | |
$c->other[] = true; | |
$c->other[0] = 2; | |
var_dump($c->other); | |
$c->more = array(); | |
$d = $c->more; | |
$d[] = 1; | |
var_dump($d); | |
var_dump($c->more); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment