Re: constructing class

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Lorderon wrote:
> I want to create an instance of a class and construct it with different
> params. The class name is a variable and the params change in each class.
> Is
> there a way to pass params to the constructor of a class like you pass
> params in the function call_user_func_array() ?

PHP has built-in functions for constructor (and destructor in 5 (4.x?)).

I don't think they take any arguments, however.

You could write your own function, such as:

$object = build('className', array('var1'=>'val1', 'var2'=>'val2'));

function build($class, $fields){
  $result = new $class();
  while (list($k, $v) = each($fields)){
    $result->$k = $v;
  }
}

There are also, in PHP 5, some nifty new "setter" and "getter" functions,
so that you can write $result->$k($v) if that makes you feel better, or if
you *NEED* to have the object call complex functions when the values are
initialized.

Hope that helps.

For sure, the "eval" solution is pretty grungy and will give you headaches
sooner or later.  Or both sooner and later.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux