Skip to content

Instantly share code, notes, and snippets.

@gggeek
Last active December 12, 2022 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gggeek/fda6e3a4d3bc52652859e8c7e9849996 to your computer and use it in GitHub Desktop.
Save gggeek/fda6e3a4d3bc52652859e8c7e9849996 to your computer and use it in GitHub Desktop.
playing around with emulation of array dynamic properties using __get, __set
<?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