1

I have this problem:

<?php

class A {
}

class B {
}

$objectsInArray = array();
$objectsInArray[] = new A();
$objectsInArray[] = new B();

class C {
    private $a;
    private $b;
    public function __construct(A $a, B $b) {
        $this->a = $a;
        $this->b = $b;
    }
}

How can I pass $objectInArray to class C() directly like this:

$c = new C($objectsInArray);

without this error message:

Catchable fatal error: Argument 1 passed to C::__construct() must be an instance of A, array given...

and i don't want this reason:

class C {
    private $a;
    private $b;
    public function __construct(array $arguments) {
        foreach ($arguments as $argument) {
            if ($argument instanceof A) {
                $this->a = $argument;
            } elseif ($argument instanceof B) {
                $this->b = $argument;
            } else {
                throw new exception('Arguments are bad!');
            }
        }
    }
}

Thanks for answers.

  • 1
    I think you need reflection, http://stackoverflow.com/questions/8734522/dynamically-call-class-with-variable-number-of-parameters-in-the-constructor – Waleed Khan Feb 01 '13 at 15:11
  • My colleague told me that is slow solution. Is it true? If is a true then how much is slow? – Tomáš Lebeda Feb 01 '13 at 15:38
  • Your colleague is right. Reflection is slow. And also it is bad practice to use reflection without special needs. Why do you need reflection here? You can, as I understand, just encapsulate $objectsInArray into the new class D, create two objects say d and e, then add to them new A, new B and pass them to the constructor. What is problem? – Andrii Tykhonov Feb 05 '13 at 13:40
  • I'll use reflection in exceptional cases and i don't need not so much. I read any articles about this problem and it's noticeably slow just when i'm using more. I need just asseble small objects. Is better to use something else? – Tomáš Lebeda Feb 05 '13 at 19:07
  • I tried to implements reflection to my framework and find out, that it's solution is not for me. Cause I need return instance of my class not reflection class. I used your solution. THX. – Tomáš Lebeda Feb 06 '13 at 08:34

1 Answers1

0

You can declare class C as you already declared but also I suggest you to implement A and B which will have array property which will hold all needed values. So then you can just create instances of A and B and get appropriate values, e. g.: $a->getElements()

 class A {
     private $a;
     public addElement($element) {
         // add element to the array $a
     }
     public getElements() {
          return $a;
     }
 }

The same for B class. Or even you can create parent class with common functionality for A and B.

So A and B will just encapsulates the array functionality and you can just do manipulating by these instances but not of array.

Then you can pass instances of A and B to the constructor of C without any problem.

Andrii Tykhonov
  • 538
  • 6
  • 11