Вызов экземпляр другого класса в качестве аргумента Анонимной функции выдает ошибку PHP 7

Mepcuk

Новичок
Вызов экземпляр другого класса в качестве аргум
Даны три класса - необходимо получить render

/*
Book record: #1
Address: 33 Market street, London, Greater London, EC4 MB5, GB
Contact #1: <[email protected]> John Doe
Contact #2: <[email protected]> Anna Baker
Book record: #2
Address: 22 Tower Street, SK4 1HV, GB
Contact #1: <[email protected]> Ms Dane Rovens
*/
Получаю ошибку
Fatal error: Uncaught TypeError: Argument 1 passed to Book::createAddress() must be an instance of Address, instance of Closure given, called in

Классы менять можно, а index.php нельзя.
Не понимаю как решить?
В моем понятии при создании обьекта Book в методе __onconstruct необходимо создать экземпляр класса Address, но класс Book задекларирован раньше, и class Book extends Address не работает.
Этот созданный экземпляр класса Address использовать в анонимной функции createAddress(Address $address), но как его туда передать не могу понять. Подскажите пожалуйста.


index.php
PHP:
<?php
 
require_once dirname(__FILE__).'/book.php';
require_once dirname(__FILE__).'/address.php';
require_once dirname(__FILE__).'/contact.php';
 
# Create first contact
$contact = new Contact;
$contact->setName('Mr John Doe');
$contact->setEmail('[email protected]');
 
# Add first contact to list of contacts
$contacts[] = $contact;
 
# Create second contact
$contact = new Contact;
$contact->setName('Ms Anna Baker')->setEmail('[email protected]');
 
# Add second contact to list of contacts
$contacts[] = $contact;
//
# Open new book
$book = new Book;
//var_dump($book);
# Add first address with both contacts
$book->createAddress(function(Address $address) use ($contacts){
    $address->setHouseNumber('33');
    $address->setStreet('Market street')->setCity('London');
    $address->setPostCode('EC4 MB5');
    $address->setCounty('Greater London');
    $address->setCountry('GB');
 
    foreach($contacts as $contact){
        $address->addContact($contact);
    }
});
 
# Reset contact list
$contacts = [];
 
# Create first contact
$contact = new Contact;
$contact->setName('Ms Dane Rovens');
$contact->setEmail('[email protected]');
 
# Add first contact to list of contacts
$contacts[] = $contact;
 
# Add second address with one contact
$book->createAddress(function(Address $address) use ($contacts) {
    $address->setHouseNumber('22');
    $address->setStreet('Tower street');
    $address->setPostCode('SK4 1HV');
    $address->setCountry('GB');
 
    foreach($contacts as $contact){
        $address->addContact($contact);
    }
})
 
# Output all of the known information
->render();
# preview of expected output below
/**
 
Book record: #1
Address: 33 Market street, London, Greater London, EC4 MB5, GB
Contact #1: <[email protected]> John Doe 
Contact #2: <[email protected]> Anna Baker
Book record: #2
Address: 22 Tower Street, SK4 1HV, GB
Contact #1: <[email protected]> Ms Dane Rovens
**/
address.php
PHP:
<?php
 
class Address{
 
    private $houseNumber = '';
    private $street = '';
    protected $city = '';
    protected $county = '';
    public  $postcode = '';
    public  $country = '';
    private $contacts = [];
        
    public function __construct($houseNumber = '', $street = '', $city = '', $county = '', $postcode = '', $country = '', $contacts = []) {
        $this->contacts[]   = $contacts;
        $this->houseNumber  = $houseNumber;
        $this->street       = $street;
        $this->city         = $city;
        $this->county       = $county;
        $this->postcode     = $postcode;
        $this->country      = $country;
    }
    
        
    public function addContact($contactValue){
        $this->contacts[] = $contactValue;
    }
    
  //  public function createAddress(Address $address){
  //        $this->records[] = $address;
  //  }
        
    public function setHouseNumber($houseNumberValue){
        $this->houseNumber = $houseNumberValue;
    }
    public function setStreet($streetValue){
        $this->street = $streetValue;
        return $this;
    }
    public function setCity($cityValue){
        $this->city = $cityValue;
    }
    public function setPostCode($postcodeValue){
        $this->postcode = $postcodeValue;
    }
    public function setCounty($countyValue){
        $this->county = $countyValue;
    }
    public function setCountry($countryValue){
        $this->country = $countryValue;
    }
}
contact.php
PHP:
<?php
 
class Contact {
    
    private $name = '';
    public $email = '';
        
        public function __construct($name = '',$email = '') {
            $this->name  = $name;
            $this->email = $email;
        }
 
    public function setName($name){
        $this->name = $name;
            return $this;
        }
    public function setEmail($email) {
            $this->email = $email;
        }
        public function getName() {
            $shortName = $name;
            return $shortName;
        }
    public function getEmail() {
            return $this->email;
        }
 
}
book.php
PHP:
<?php
 
class Book{
 
    private $records = []; 
        
        public function __construct(array $records = []) {
            
            $this->records[] = $records;
            $this->createClass();
        }
        
        public function createClass(){
            $address = new Address();
            return $address;
        }
        
 
    public function createAddress(Address $address){
        $this->records[] = $address;
        }
//        public function getIterator() {
//            //yield from $this->records;
//            return new ArrayIterator($this);
//        }
 
    public function render(){
 
        $output = [];
 
        foreach($this->records as $index => $record){
 
            $output[] = 'Book record #'.($index+1);
 
            $output[] = $record['address']->getHouseNumber();
 
            foreach($record['contacts'] as $index => $contact){
                $output[] = 'Contact #'.($index+1).': <'.$contact->getEmail().'> '.$contact->getName();
                        }
 
        }
                var_dump($output);
    }
}
ента Анонимной функции выдает ошибку PHP 7
 

флоппик

promotor fidei
Команда форума
Партнер клуба
У тебя ошибка не там. В createAddress ты не вызываешь анонимную функцию, ты ее просто объявляешь, и пытаешься передать ее аргументом. Судя по закомментированному куску, нужно убрать тайп-хинт Address из функции createAddress, внутри получить эту кложуру, и вызывать ее с аргументом, который получаешь от ::createClass()
В реальности конечно, так делать вообще не надо.
 

fixxxer

К.О.
Партнер клуба
createClass в классе Book - бессмысленная фигня, которая ничего не делает. Убери нафиг и метод, и его вызов из конструктора.

Если исходить из постановки задачи (index.php менять почему-то нельзя), пусть будет так:
PHP:
/**
* Address|callable $address
*/
public function createAddress($address) {
    if (is_callable($address)) {
        $fn = $address;
        $address = new Address();
        $result = $fn($address);
        if ($result instanceof Address) {
            $address = $result;
        }
    }
    if ($address instanceof Address) {
         $this->records[] = $address;
    }
    throw new \InvalidArgumentException();
}
Но это какое-то извращение.
 
Сверху