03-24-2008, 10:54 AM
|
#6 (permalink)
|
|
The Frequenter
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
|
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
|
|
|