@Mepcuk
Учиться никогда не поздно

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

Даны три класса - необходимо получить render

/*
Book record: #1
Address: 33 Market street, London, Greater London, EC4 MB5, GB
Contact #1: John Doe
Contact #2: Anna Baker
Book record: #2
Address: 22 Tower Street, SK4 1HV, GB
Contact #1: 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
 
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('john@doe.com');
 
# Add first contact to list of contacts
$contacts[] = $contact;
 
# Create second contact
$contact = new Contact;
$contact->setName('Ms Anna Baker')->setEmail('anna@baker.com');
 
# 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('dane@rovens.com');
 
# 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: <john@doe.com> John Doe 
Contact #2: <anna@baker.com> Anna Baker
Book record: #2
Address: 22 Tower Street, SK4 1HV, GB
Contact #1: <dane@rovens.com> Ms Dane Rovens
**/

address.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
 
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
 
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);
    }
}
  • Вопрос задан
  • 218 просмотров
Решения вопроса 1
DevMan
@DevMan
в чем вопрос то?
public function createAddress(Address $address)
явно прописывает тип аргумента и ругается когда ему суют не его.
не нравится? уберите/поменяйте тип.
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
@karminski
Senior React.JS Developer
Функция createAddress принимает в качестве аргумента объект класса Address, а вы ей замыкание подсовываете. Просто вы забыли в замыкании вернуть вернуть объект типа адрес.

# 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);
    }

    return $address;
});
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы