I'm trying to come up with a graceful way to create C#-esque properties in PHP
Right now, I have:
class Example
{
private $allowedProps = array('prop1', 'prop2', 'prop3');
private $data = array();
public function __set($propName, $propValue)
{
if (in_array($propName, $this->allowedProps))
{
// set property
}
else
{
// error
}
}
public function __get($propName)
{
if (array_key_exists($propName, $this->data))
{
// get property
}
else
{
// error
}
}
}
In the commented out sections, for something more complex than simply writing to or retrieving from the $data
array, the easiest thing to do would be to simply branch logic where necessary with an if-else
or switch
. That's messy, though, and runs counter to what I want. Is there a way to invoke a callback function that would have access to the $data
array?
EDIT: Seems like the simplest thing to do would be:
class Example
{
private $allowedProps = array('prop1', 'prop2', 'prop3');
private $data = array();
public function __set($propName, $propValue)
{
$propName = strtolower($propName);
if (in_array($propName, $this->allowedProps))
{
$funcName = "set" . ucfirst($propName);
$this->$funcName($propValue);
}
else
{
// error
}
}
public function __get($propName)
{
$propName = strtolower($propName);
if (array_key_exists($propName, $this->data))
{
$funcName = "get" . ucfirst($propName);
$this->$funcName();
}
else
{
// error
}
}
private function getProp1()
{
// do stuff, and return the value of prop1, if it exists
}
// ...
}
I'm not sure if having a host of private setter and getter methods is the way to go. Lambdas would probably be ideal, but they're only available in PHP 5.3+.