简体   繁体   中英

How to pass 2 object in array to constructor automatically with PHP

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.

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, eg: $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM