Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/topic.php on line 737
Форумы портала PHP.SU :: Вызов экземпляр другого класса в качестве аргумента Анонимной фунцией Closure

 PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи


 Страниц (1): [1]   

> Описание: Вызов экземпляр другого класса в качестве аргумента Анонимной фунцией Closure
Mepcuk
Отправлено: 05 Декабря, 2019 - 00:17:11
Post Id


Новичок


Покинул форум
Сообщений всего: 1
Дата рег-ции: Дек. 2019  


Помог: 0 раз(а)




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

/*
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
*/
Получаю ошибку
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:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3.  
  4. require_once dirname(__FILE__).'/book.php';
  5. require_once dirname(__FILE__).'/address.php';
  6. require_once dirname(__FILE__).'/contact.php';
  7.  
  8. # Create first contact
  9. $contact = new Contact;
  10. $contact->setName('Mr John Doe');
  11. $contact->setEmail('john@doe.com');
  12.  
  13. # Add first contact to list of contacts
  14. $contacts[] = $contact;
  15.  
  16. # Create second contact
  17. $contact = new Contact;
  18. $contact->setName('Ms Anna Baker')->setEmail('anna@baker.com');
  19.  
  20. # Add second contact to list of contacts
  21. $contacts[] = $contact;
  22. //
  23. # Open new book
  24. $book = new Book;
  25. //var_dump($book);
  26. # Add first address with both contacts
  27. $book->createAddress(function(Address $address) use ($contacts){
  28.     $address->setHouseNumber('33');
  29.     $address->setStreet('Market street')->setCity('London');
  30.     $address->setPostCode('EC4 MB5');
  31.     $address->setCounty('Greater London');
  32.     $address->setCountry('GB');
  33.  
  34.     foreach($contacts as $contact){
  35.         $address->addContact($contact);
  36.     }
  37. });
  38.  
  39. # Reset contact list
  40. $contacts = [];
  41.  
  42. # Create first contact
  43. $contact = new Contact;
  44. $contact->setName('Ms Dane Rovens');
  45. $contact->setEmail('dane@rovens.com');
  46.  
  47. # Add first contact to list of contacts
  48. $contacts[] = $contact;
  49.  
  50. # Add second address with one contact
  51. $book->createAddress(function(Address $address) use ($contacts) {
  52.     $address->setHouseNumber('22');
  53.     $address->setStreet('Tower street');
  54.     $address->setPostCode('SK4 1HV');
  55.     $address->setCountry('GB');
  56.  
  57.     foreach($contacts as $contact){
  58.         $address->addContact($contact);
  59.     }
  60. })
  61.  
  62. # Output all of the known information
  63. ->render();
  64. # preview of expected output below
  65. /**
  66.  
  67. Book record: #1
  68. Address: 33 Market street, London, Greater London, EC4 MB5, GB
  69. Contact #1: <john@doe.com> John Doe
  70. Contact #2: <anna@baker.com> Anna Baker
  71. Book record: #2
  72. Address: 22 Tower Street, SK4 1HV, GB
  73. Contact #1: <dane@rovens.com> Ms Dane Rovens
  74. **/
  75. address.php
  76.  


PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3.  
  4. class Address{
  5.  
  6.     private $houseNumber = '';
  7.     private $street = '';
  8.     protected $city = '';
  9.     protected $county = '';
  10.     public  $postcode = '';
  11.     public  $country = '';
  12.     private $contacts = [];
  13.        
  14.     public function __construct($houseNumber = '', $street = '', $city = '', $county = '', $postcode = '', $country = '', $contacts = []) {
  15.         $this->contacts[]   = $contacts;
  16.         $this->houseNumber  = $houseNumber;
  17.         $this->street       = $street;
  18.         $this->city         = $city;
  19.         $this->county       = $county;
  20.         $this->postcode     = $postcode;
  21.         $this->country      = $country;
  22.     }
  23.    
  24.        
  25.     public function addContact($contactValue){
  26.         $this->contacts[] = $contactValue;
  27.     }
  28.    
  29.   //  public function createAddress(Address $address){
  30.   //        $this->records[] = $address;
  31.   //  }
  32.        
  33.     public function setHouseNumber($houseNumberValue){
  34.         $this->houseNumber = $houseNumberValue;
  35.     }
  36.     public function setStreet($streetValue){
  37.         $this->street = $streetValue;
  38.         return $this;
  39.     }
  40.     public function setCity($cityValue){
  41.         $this->city = $cityValue;
  42.     }
  43.     public function setPostCode($postcodeValue){
  44.         $this->postcode = $postcodeValue;
  45.     }
  46.     public function setCounty($countyValue){
  47.         $this->county = $countyValue;
  48.     }
  49.     public function setCountry($countryValue){
  50.         $this->country = $countryValue;
  51.     }
  52. }
  53.  

contact.php
PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3.  
  4. class Contact {
  5.    
  6.     private $name = '';
  7.     public $email = '';
  8.        
  9.         public function __construct($name = '',$email = '') {
  10.             $this->name  = $name;
  11.             $this->email = $email;
  12.         }
  13.  
  14.     public function setName($name){
  15.         $this->name = $name;
  16.             return $this;
  17.         }
  18.     public function setEmail($email) {
  19.             $this->email = $email;
  20.         }
  21.         public function getName() {
  22.             $shortName = $name;
  23.             return $shortName;
  24.         }
  25.     public function getEmail() {
  26.             return $this->email;
  27.         }
  28.  
  29. }
  30.  

book.php
PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3.  
  4. class Book{
  5.  
  6.     private $records = [];
  7.        
  8.         public function __construct(array $records = []) {
  9.            
  10.             $this->records[] = $records;
  11.             $this->createClass();
  12.         }
  13.        
  14.         public function createClass(){
  15.             $address = new Address();
  16.             return $address;
  17.         }
  18.        
  19.  
  20.     public function createAddress(Address $address){
  21.         $this->records[] = $address;
  22.         }
  23. //        public function getIterator() {
  24. //            //yield from $this->records;
  25. //            return new ArrayIterator($this);
  26. //        }
  27.  
  28.     public function render(){
  29.  
  30.         $output = [];
  31.  
  32.         foreach($this->records as $index => $record){
  33.  
  34.             $output[] = 'Book record #'.($index+1);
  35.  
  36.             $output[] = $record['address']->getHouseNumber();
  37.  
  38.             foreach($record['contacts'] as $index => $contact){
  39.                 $output[] = 'Contact #'.($index+1).': <'.$contact->getEmail().'> '.$contact->getName();
  40.                         }
  41.  
  42.         }
  43.                 var_dump($output);
  44.     }
  45. }
  46.  
 
 Top
LIME
Отправлено: 05 Декабря, 2019 - 10:32:19
Post Id


Активный участник


Покинул форум
Сообщений всего: 10732
Дата рег-ции: Нояб. 2010  


Помог: 322 раз(а)




офигенные анемичные модели
ну да фиг с ними
PHP:
скопировать код в буфер обмена
  1. $address = new Address('33', 'Street Lenina', ...);// это конструктор
  2. $book->createAddress($address);
 
 Top
LIME
Отправлено: 05 Декабря, 2019 - 12:38:46
Post Id


Активный участник


Покинул форум
Сообщений всего: 10732
Дата рег-ции: Нояб. 2010  


Помог: 322 раз(а)




PHP:
скопировать код в буфер обмена
  1. $book->createAddress(new Address('33', 'Street Lenina', ...));

(Добавление)
PHP:
скопировать код в буфер обмена
  1. $book->createAddress(
  2.     (new Address())
  3.         ->setHouseNumber('22')
  4.         //...
  5.         ->setCounty('США');
  6. );
 
 Top
Страниц (1): [1]
Сейчас эту тему просматривают: 0 (гостей: 0, зарегистрированных: 0)
« Объектно-ориентированное программирование »


Все гости форума могут просматривать этот раздел.
Только зарегистрированные пользователи могут создавать новые темы в этом разделе.
Только зарегистрированные пользователи могут отвечать на сообщения в этом разделе.
 



Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB