Reputation: 1503
I am confused about constructor. I need to pass an array to a class. I have at the moment 2 data to pass to the array.
Now from this array, I need to define $this->m_id
and $this->community_type
so that I can use these variables through out the class. Below is my example.
$arr = array('id'=>$u_id, 'community_type' => $community_type);
$rate = new Registration($arr);
class Registration{
protected $m_id;
protected $community_type;
public function __construct(array $arr = array())
{
foreach ($arr as $key => $value) {
$this->$key = $value;
}
}
}
I am looking to set
$this->m_id = $m_id;
$this->community_type = $community_type;
I tried using a for
loop but I don't know something went wrong.
Can anybody help me
Upvotes: 0
Views: 242
Reputation: 2644
When run in the terminal, it shows that the object's properties are being created dynamically exactly as one would expect:
php > class Registration{
php { protected $m_id;
php { protected $community_type;
php {
php { public function __construct(array $arr = array())
php { {
php { foreach ($arr as $key => $value) {
php { $this->$key = $value;
php { }
php { }
php { }
php > $u_id = 'u_id value';
php > $community_type = 'community type value';
php >
php > $arr = array('id'=>$u_id, 'community_type' => $community_type);
php > $rate = new Registration($arr);
php >
php > var_dump($rate);
object(Registration)#1 (3) {
["m_id":protected]=>
NULL
["community_type":protected]=>
string(20) "community type value"
["id"]=>
string(10) "u_id value"
}
I think there were several confounding factors that may have tripped you up:
$u_id
and $community_type
variables assigned? They weren't in your code.$m_id
vs $u_id
, ['id']
vs $this->m_id
The var_dump shows that the keys of your array (['id']
and ['community_type']
were indeed assigned as properties of the object.
Upvotes: 1
Reputation: 31397
You could try $array[your_array_key]
as follow
public function __construct(array $arr = array())
{
$this->m_id = $arr['id'];
$this->community_type = $arr['community_type'];
}
Your existing code should work, if you are trying through loop, only problem I could notice is,
protected $m_id;
You need to change this to
protected $id;
Because, in your loop you are assuming your key is the member variable, which is actually not.
foreach ($arr as $key => $value) {
$this->$key = $value;
}
In you are array, your first key is id
where as member variable declared as m_id
, which is not matching.
Upvotes: 1