Thread: array to object
View Single Post
Old 03-24-2008, 10:54 AM   #6 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Hi Gibou,

The problem with your code is:

PHP Code:
if(isset($this->$key)) 
This will return false for each of your variables as they are set to NULL. You can overcome this problem by giving them a default value - ie, something like the following:

PHP Code:
<?php
class Test
{

    private 
$id 0;
    private 
$title '';
    private 
$url '';
    private 
$story '';
    
    public function 
__construct($params)
    {

        if(!empty(
$params) && is_array($params))
        {
            foreach(
$params as $key => $val)
            {
                if (isset(
$this->$key))
                {
                    
$this->$key $val;
                }
            }
        }
    }

}

$args = array(
    
'id' => 1,
    
'title' => 'My Article',
    
'url' => 'http://www.talkphp.com',
    
'story' => 'something here...'
);

$test = new Test($args);

var_dump($test);
Will result in:

Code:
object(Test)#1 (4) {
  ["id:private"]=>
  int(1)
  ["title:private"]=>
  string(10) "My Article"
  ["url:private"]=>
  string(22) "http://www.talkphp.com"
  ["story:private"]=>
  string(17) "something here..."
}
Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following User Says Thank You to Alan @ CIT For This Useful Post:
Gibou (03-24-2008)