L
L
link002014-12-14 15:03:32
PHP
link00, 2014-12-14 15:03:32

How are these two articles different (polymorphism, PHP)?

Whether I'm dumb =) I won't enter at all, there are two articles on Habré about polymorphism. 1st article habrahabr.ru/post/37576 2nd article habrahabr.ru/post/37610 In the 2nd article, the author writes that he read the first one, and there is not quite polymorphism in it. And he gives an example. After the example, he writes the phrase "the whole point is in the end of the code." But the ending of the code is NOTHING different, except for passing $id as a parameter. Damn, is that what he means? Poke pliz with your nose, what is the PRINCIPAL difference between these examples, and why EXACTLY in the second "canonical" polymorphism?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Alexey Yakhnenko, 2014-12-14
@link00

the code in the articles is no different.
why the hell the author of #2 decided to show off, and explain "What is polymorphism really" using exactly the same example - will remain a mystery for centuries.
None of them convinced me personally.
I'll try to give my own example:

<?php 

// базовый класс публикации
// имеет свойства для заголовка и тела
// умеет отдавать контент в простейшем виде
class Publication {
  protected $_header;
  protected $_body;
  
  public function __construct($header, $body) {
    $this->_header = $header;
    $this->_body = $body;
  }

  public function getContent() {
    return 
      '<h1>' . $this->_header .  '</h1>' . 
      '<p>' . $this->body . '</p>';
  }
}

// статья в дополнение имеет еще свойство для имени автора
// конструктор переопределен для задания имени автора
// метод getContent переопределен, чтобы дописывать под заголовком статьи имя автора
class Article extends Publication {
  protected $_author;
  
  public function __construct($header, $body, $author) {
    parent::__construct($header, $body);
    
    $this->_author = $author;
  }

  public function getContent() {
    return 
      '<h1>' . $this->_header .  '</h1>' . 
      '<br /><br/ >'. 
      'By ' . $this->author . 
      '<br /><br/ >'. 
      '<p>' . $this->body . '</p>';
  }
}

// объявление переопределяет только метод getContent 
// заворачивает вывод в блок определенного класса - так объявление заметнее
// но сам контент генерируется родительским методом
class Announcement extends Publication {
  public function getContent() {
    return 
      '<div class="announcement">' . 
        parent::getContent() . 
      '</div>';
  }
}

// а вот короткая новость, например, не переопределяет метод getContent
// он ей подходит как есть
// она только с данными немного шаманит
class ShortNews extends Publication {
  public function __construct($header, $body) {
    $this->_body = substr($header, 0, 31);
    $this->_body = substr($body, 0, 255);
  }
}

// а вот и принтер
// принтер печатает публикации
// ему пофиг, какие именно - хоть короткую новость мы его попросим напечатать, хоть объявление
// он знает, что у любой публикации есть метод getContent, результат которого можно напечатать
// потому что объекты классов статья/объявление/короткая новость - они одновременно и объекты класса публикация
// это и есть полиморфизм
class PublicationPrinter {
  public static function print(Publication $publication) {
    print($publication->getContent());
  }
}

A
Anton Shamanov, 2014-12-14
@SilenceOfWinter

It also says: "We use the same code for objects of different classes."

K
kstyle, 2017-04-19
@kstyle

c=a/(1/b))

N
Nikolai Chuprik, 2017-04-19
@choupa

1. Add in a cycle.
2. Use the identity a*b = exp( ln(a) + ln(b) )
3. Send two numbers to the client, let him multiply in JS and return back to PHP

S
shagguboy, 2017-04-19
@shagguboy

put in a loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question