Передавать переменное число переменных в класс в PHP
Мне нужно передать переменное количество строк для создания экземпляров разных классов. Я всегда могу переключиться на размер массива:
switch(count($a)) {
case 1:
new Class(${$a[0]});
break;
case 2:
new Class(${$a[0]}, ${$a[1]});
break;
etc...
Должен быть лучший способ сделать это. Если у меня есть массив строк ( "variable1", "variable2", "variable3",...), как я могу создать экземпляр класса без учета вручную каждой возможности?
Ответы
Ответ 1
Если вы должны сделать это таким образом, вы можете попробовать:
$variable1 = 1;
$variable2 = 2;
$variable3 = 3;
$variable4 = 4;
$varNames = array('variable1', 'variable2', 'variable3', 'variable4');
$reflection = new ReflectionClass('A');
$myObject = $reflection->newInstanceArgs(compact($varNames));
class A
{
function A()
{
print_r(func_get_args());
}
}
Ответ 2
<?php
new Example($array);
class Example
{
public function __construct()
{
foreach (func_get_args() as $arg)
{
// do stuff
}
}
}
Ответ 3
// Constructs an instance of a class with a variable number of parameters.
function make() { // Params: classname, list of constructor params
$args = func_get_args();
$classname = array_shift($args);
$reflection = new ReflectionClass($classname);
return $reflection->newInstanceArgs($args);
}
Как использовать:
$MyClass = make('MyClass', $string1, $string2, $string3);
Изменить: если вы хотите использовать эту функцию с вашим $a = array ( "variable1", "variable2", 'variable3 ",...)
call_user_func_array('make', array_merge(array('MyClass'), $a));
Ответ 4
Вы можете использовать массив для передачи переменной числа переменной в класс, например:
<?php
class test
{
private $myarray = array();
function save($index, $value)
{
$this->myarray[$index] = $value;
}
function get($index)
{
echo $this->myarray[$index] . '<br />';
}
}
$test = new test;
$test->save('1', 'some value here 1');
$test->save('2', 'some value here 2');
$test->save('3', 'some value here 3');
$test->get(1);
$test->get(2);
$test->get(3);
?>
Выход
some value here 1
some value here 2
some value here 3
Вы также можете использовать __ get и __set magic methods, чтобы легко сохранять информацию.
Ответ 5
Кажется, что отражение может вытащить из шляпы. Это приносит вам любезность примечания PHP call_user_func_array. Следующий код создаст класс, вызвав конструктор с содержимым вашего массива.
<?php
// arguments you wish to pass to constructor of new object
$args = array('a', 'b');
// class name of new object
$className = 'ClassName';
// make a reflection object
$reflectionObj = new ReflectionClass($className);
// use Reflection to create a new instance, using the $args
$command = $reflectionObj->newInstanceArgs($args);
// this is the same as: new myCommand('a', 'b');
?>
Ответ 6
Посмотрите здесь. Помогает ли метод 2? Кроме того, возможно, переместив переключатель в конструктор (если это практически), вы сможете скрыть это от остальной части кода.
Ответ 7
взгляните на шаблон дизайна factory:
class Factory {
public static function CreateInstance($args) {
switch(func_get_num_args()) {
case …:
return new ClassA(…); break;
case …:
return new ClassB(…); break;
}
}
}