Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created January 26, 2018 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/cd3e2afb65810ed9cf423ad7c8f8e532 to your computer and use it in GitHub Desktop.
Save tommcfarlin/cd3e2afb65810ed9cf423ad7c8f8e532 to your computer and use it in GitHub Desktop.
[OOP Fundamentals] Looking At Polymorphism In-Depth
<?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;
}
}
<?php
class Post extends Content {
private $author;
public function __construct() {
parent::__construct();
$this->author = "Tom McFarlin";
}
public function getAuthor()
{
return $this->author;
}
}
<?php
class Page extends Content {
private $category;
public function __construct() {
parent::__construct();
$this->category = "Articles";
}
public function getCategory()
{
return $this->category;
}
}
<?php
$content = new Content();
echo $content->getTitle();
<?php
// These will work because they reside in the Content base class.
$post = new Post();
echo $post->getAuthor();
echo $post->getTitle();
<?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