私はこの問題を抱えています:
<?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;
}
}
次のように、 $ objectInArrayをクラスC()に直接渡すにはどうすればよいですか。
$c = new C($objectsInArray);
このエラーメッセージなし:
Catchable fatal error: Argument 1 passed to C::__construct() must be an instance of A, array given...
そして私はこの理由を望んでいません:
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!');
}
}
}
}
回答ありがとうございます。