You are here: Re: [PHP] ability to use extract to $this vars in a class « PHP « IT news, forums, messages
Re: [PHP] ability to use extract to $this vars in a class

Posted by Jochem Maas on 02/09/05 12:31

Guillermo Rauch wrote:
> If i understand you correctly, you want to extract all the keys and
> generate class members with them..
>
> // Define class test
> class test {
> // We pass an array to the constructor
> function __construct( $arr ) {
> foreach($arr as $key => $val ) {
> $this->{$key} = $val;
> }
> // For this example, i print the structure of the object
> print_r($this);
> }
> }
>
> $tests = array( 'hi' => 'bye', 'hey' => 'ho', 'lets' => 'go');
> $test = new test($tests);
>
> I forgot in the previous message to mention that if the member exists,
> it will be overriden. In addition, you shouldn't use this, as you
> don't have control over the accessing to the vars. Instead, you should
> store them in a previously defined array (for example private $_vars;
> )

another way to control access:

class test {
private function __construct() {}

function __get($var, $val)
{
$r = (isset($this->$var))
? isset($this->$var
: null;

return $r;
}

function __set($var, $val)
{
// do some magic here
}

public static function make($arr)
{
$t = new test;
foreach($arr as $key => $val ) {
$t->$key = $val;
}
return $t;
}
}

$t = test::make(array('one' => '1', 'two' => '2'));


>

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация