I have 3 classes
<?php
namespace App;
class Address {
private $houseNumber = '';
private $street = '';
protected $city = '';
protected $county = '';
public $postcode = '';
public $country = '';
private $contacts = [];
public function setHouseNumber($provided_housenumber){
$this->houseNumber = $provided_housenumber;
return $this;
}
public function setStreet($provided_street){
$this->street = $provided_street;
return $this;
}
public function setPostCode($provided_postcode){
$this->postcode = $provided_postcode;
return $this;
}
public function setCounty($provided_county){
$this->county = $provided_county;
return $this;
}
public function setCountry($provided_country){
$this->country = $provided_country;
return $this;
}
}
Second class
<?php
namespace App;
class Book {
private $records = [];
public function createAddress(Address $address) {
$this->records[] = $address;
}
}
And third class
<?php
namespace App;
class Contact {
private $name = '';
public $email = '';
public function setName($provided_name){
$this->name = $provided_name;
return $this;
}
public function setEmail($provided_mail){
$this->email = $provided_mail;
return $this;
}
}
Then in index file I'm calling Book method like this:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use App\Contact;
use App\Book;
use App\Address;
# Create first contact
$contact = new Contact;
$contact->setName('Mr John Doe');
$contact->setEmail('[email protected]');
# Add first contact to list of contacts
$contacts[] = $contact;
# Open new book
$book = new Book;
# Add first address with both contacts
$book->createAddress(function(Address $address) use ($contacts){ //<---- Here it throws Fatal error: Uncaught TypeError: Argument 1 passed to App\Book::createAddress() must be an instance of App\Address, instance of Closure given
$address->setHouseNumber('33');
$address->setStreet('Example street')->setCity('Cambridge');
$address->setPostCode('CBF MB5');
$address->setCounty('Cambridgeshire');
$address->setCountry('GB');
foreach($contacts as $contact){
$address->addContact($contact);
}
});
So what I'm tiring to do in index file - in new instance of Book I'm executing method createAddress() by wrapping it all up in anonymous function (closure function).
Than in that function I set all variables and pass it to the Book. But somehow I can not call Class in closure function as argument -
Fatal error: Uncaught TypeError: Argument 1 passed to App\Book::createAddress() must be an instance of App\Address, instance of Closure given
So I definitely am missing something fundamental here, can somebody guide me through?
createAddressrequiresAddressinstance, you passClosure. What's is unclear here?Closureis not instance ofAddress.createAddress()not require anAddressobject as parameter or don't use a closure but create anew Address()object and pass that as parameter