, . () , - Traversable, .
, :
, , ,
, , PHP "" (O (1) vs O (n) ). , __get __set. . :
class Declared
{
private $foo = 123;
public function setFoo($val)
{
$this->foo = (int) $val;
return $this;
}
public function getFoo()
{
return $this->foo;
}
public function __get($name)
{
$name = 'get'.ucfirst($name);
if (method_exists($this, $name))
{
return $this->{$name}():
}
throw new RuntimeExcpetion('attempted to access non-existing property using '.$name.' in '.__METHOD__);
}
public function __set($name, $val)
{
$mname = 'set'.ucfirst($name);
if (method_exists($this, $mname))
{
return $this->{$mname}($val):
}
throw new RuntimeException($name.' is an invalid property name');
}
}
, , , , - , / . $foo , , int. __set, messier, ( if else).
, , :
class NotDeclared
{
private $data = array('foo' => 123);
public function __get($name)
{
return isset($this->data[$name]) ? $this->data[$name] : null;
}
public function __set($name, $value)
{
$this->[$data] = $value;
}
}
, , . , :
$declared = new Declared;
$notDeclared = new NotDeclared;
echo $declared->foo;
echo $declared->getFoo();
echo $notDeclared->foo;
$declared->foo = 34;
$declared->setFoo($declared->foo*2);
echo $declared->fo;
echo $notDeclared->fo;
$notDeclared->fo = 'Typo, meant foo, but assign string to expected integer property';
$declared->fo = 'asd';
echo $notDeclared->foo;
__set, excpetions, , excpetion. , , , , , , fo
: , :
$instance->newProperty;
?
- ,
newProperty newProperty ( )__get- invoke
__get- (
$this->data) newProperty (isset)- (.. null)
, $instance->newProperty PHP newPropery, __get, $data, newPropery , null , .
.