Last active
December 22, 2015 15:04
-
-
Save pfaocle/3793916 to your computer and use it in GitHub Desktop.
PHP for CMS Developers - Classes & Exceptions exercises
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
// "Main" | |
<?php | |
/** | |
* PHP for Developers - Exercises | |
* | |
* main/testing | |
*/ | |
spl_autoload_register(function ($class_name) { | |
include $class_name . '.class.php'; | |
}); | |
// Basic Article | |
$article = new Article('Frist post', 'This is my first post here so be nice.'); | |
var_dump($article); | |
// What's the difference here? | |
print $article->title . "\n"; | |
print $article->getTitle() . "\n"; | |
print $article->getBody() . "\n"; | |
print $article->getExcerpt(20) . "\n"; | |
$sa = new SeriesArticle('Frist post', 'This is my first post here so be nice.'); | |
var_dump($sa); | |
$sa2 = new SeriesArticle('Second post', 'This is my second post.', $sa); | |
var_dump($sa2); | |
print $sa->getExcerpt(22) . "\n"; | |
try { | |
print $sa->getExcerpt('a') . "\n"; | |
} | |
catch (Exception $e) { | |
print "Invalid value passed: " . $e; | |
} | |
// Article.class.php | |
<?php | |
class Article { | |
protected $title; | |
protected $body; | |
public function __construct($title, $body) { | |
$this->title = $title; | |
$this->body = $body; | |
} | |
public function __get($property) { | |
if (property_exists($this, $property)) { | |
return $this->$property; | |
} | |
} | |
public function getTitle() { | |
return $this->title; | |
} | |
public function getBody() { | |
return $this->body; | |
} | |
public function getExcerpt($length) { | |
if (!is_int($length)) { | |
throw new UnexpectedValueException(); | |
} | |
return trim(substr($this->body, 0, $length)) . '...'; | |
} | |
} | |
// SeriesArticle.class.php | |
<?php | |
class SeriesArticle extends Article { | |
public function __construct($title, $body, SeriesArticle $previous = NULL) { | |
parent::__construct($title, $body); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment