[OOP Fundamentals] Looking At Polymorphism In-Depth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Content { | |
protected $title; | |
protected $content; | |
protected $metadata; | |
public function __construct() | |
{ | |
$this->title = "Hello World!"; | |
$this->content = "This is a sample piece of content."; | |
$this->metadata = "<This is the metadata of the post.>"; | |
} | |
public function getTitle() | |
{ | |
return $this->title; | |
} | |
public function getContent() | |
{ | |
return $this->content; | |
} | |
public function getMetadata() | |
{ | |
return $this->metadata; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Post extends Content { | |
private $author; | |
public function __construct() { | |
parent::__construct(); | |
$this->author = "Tom McFarlin"; | |
} | |
public function getAuthor() | |
{ | |
return $this->author; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Page extends Content { | |
private $category; | |
public function __construct() { | |
parent::__construct(); | |
$this->category = "Articles"; | |
} | |
public function getCategory() | |
{ | |
return $this->category; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$content = new Content(); | |
echo $content->getTitle(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// These will work because they reside in the Content base class. | |
$post = new Post(); | |
echo $post->getAuthor(); | |
echo $post->getTitle(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This will throw an error because the method doesn't reside on Content. | |
$content->getAuthor(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment