OOP Challenges
Now let's do a few simple challenges to practice what we've learned so far.
Challenge 1
- Create a class called
Articlethat has the following properties:
titlecontentpublished
-
The
publishedproperty should beprivateand have a default value offalse. -
Create a constructor that takes in the
titleandcontentas arguments and sets the values of the properties. -
Create a method called
publishthat changes the value of thepublishedproperty totrue. -
Create a method called
isPublishedthat returns the value of thepublishedproperty. Remember, it is private, so we can not access it directly outside of the class. -
Create two new instances of the
Articleclass and call thepublishmethod on one of them, which should set thepublishedproperty totrue. Then call theisPublishedmethod on both of the articles to see if they are published.
When you echo out the result of the isPublished method, you can wrap it in a var_dump or var_export function to see the actual true or false value instead of just 1 or 0.
Click For Solution
<?php
class Article
{
public $title;
public $content;
private $published = false;
public function __construct($title, $content)
{
$this->title = $title;
$this->content = $content;
}
public function publish()
{
$this->published = true;
}
public function isPublished()
{
return $this->published;
}
}
$article1 = new Article('My First Post', 'This is the first post.');
$article2 = new Article('My Second Post', 'This is the second post.');
$article1->publish();
echo var_dump($article1->isPublished(), true) . '<br>';
echo var_dump($article2->isPublished(), true) . '<br>';
Challenge 2
- Create a class called
StringUtilitythat has the following static methods:
-
shout($string)- Takes in a string and returns it in all uppercase letters with an exclamation mark added to the end. -
whisper($string)- Takes in a string and returns it in all lowercase letters with a period added to the end. -
repeat($string, $times)- Takes in a string and a number and returns the string repeated the specified number of times. Use a default value of2for the$timesparameter.
- Create a new instance of the
StringUtilityclass and call each of the methods on it.
Hints
- You can use the
strtoupperandstrtolowerfunctions to convert a string to uppercase or lowercase. - You can use the
str_repeatfunction to repeat a string a certain number of times.
Click For Solution
class StringUtility
{
public static function shout($string)
{
return strtoupper($string) . '!';
}
public static function whisper($string)
{
return strtolower($string) . '.';
}
public static function repeat($string, $times = 2)
{
return str_repeat($string, $times);
}
}