class A {
$props = array('prop1', 'prop2', 'prop3');
}
How to convert above defined array into class properties ? The final result would be..
class A {
$props = array('prop1', 'prop2', 'prop3');
public $prop1;
public $prop2;
public $prop3;
}
I have tried this so far :
public function convert(){
foreach ($this->props as $prop) {
$this->prop;
}
}
Looks bit ugly as I am new to php
You may use php magic methods __get
and __set
like this (study when and how are they invoked before implementing):
class A {
protected $props = array('prop1', 'prop2', 'prop3');
// Although I'd rather use something like this:
protected GetProps()
{
return array('prop1', 'prop2', 'prop3');
}
// So you could make class B, which would return array('prop4') + parent::GetProps()
// Array containing actual values
protected $_values = array();
public function __get($key)
{
if( !in_array( $key, GetProps()){
throw new Exception("Unknown property: $key");
}
if( isset( $this->_values[$key])){
return $this->_values[$key];
}
return null;
}
public function __set( $key, $val)
{
if( !in_array( $key, GetProps()){
throw new Exception("Unknown property: $key");
}
$this->_values[$key] = $val;
}
}
And you would use it as normal properties:
$instance = new A();
$a->prop1 = 'one';
$tmp = $a->undef; // will throw an exception
It would be also nice if you would implement:
public function __isset($key){}
public function __unset($key){}
so you'll have consistent and complete class.