Skip to content

Instantly share code, notes, and snippets.

@vadremix
Created June 10, 2016 21:51
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 vadremix/2a0b1e9f2809c00a5f7e83dba7a14bce to your computer and use it in GitHub Desktop.
Save vadremix/2a0b1e9f2809c00a5f7e83dba7a14bce to your computer and use it in GitHub Desktop.
OOP palindrome checker example
<?php
/**
* Class to create word objects.
* Includes method to check whether word is a palindrome. Can be
* extended with methods to check other properties of the word.
*
* @author James Roper <vadremix@gmail.com>
*/
class Word {
protected $word_string;
/**
* Set object property
*
* @param string $word
*/
public function __construct($word) {
$prop['word'] = $word;
// set properties, handles exception if any property is invalid
try {
$this->_set_properties($prop);
} catch (Exception $e) {
echo '<pre>Line '.$e->getTrace()[1]['line'].$e->getMessage() .'</pre>';
}
}
/**
* Sets objects properties.
* By using a method for this, we can strictly validate input
* to reduce potential for bugs.
*
* @param array $properties
* @return boolean
*/
protected function _set_properties($properties) {
if(is_string($properties['word'])) {
$this->word_string = $properties['word'];
} else {
throw new Exception(': new Word parameter should be a string.');
}
return true;
}
/**
* Returns word as string
*
* @return string
*/
public function get_word() {
return $this->word_string;
}
/**
* Checks whether object is a palindrome
*
* @return boolean
*/
public function is_palindrome() {
$word = $this->word_string;
// converts string to array with 1 character chunks
$word_array = str_split($word, 1);
// declares variable to prepare for first loop iteration
$word_reversed = '';
// string is constructed in reverse by iterating forward
// and appending each element to the beginning of a string
foreach($word_array as $char) {
$word_reversed = $char.$word_reversed;
}
// compares stings to determine if palindrome
if($word_reversed == $word) {
return true;
} else {
return false;
}
}
}
// Palindrome tests
$test[0] = new Word('cammac');
$test[1] = new Word('level');
$test[2] = new Word('bacon');
$test[3] = new Word(2112);
foreach($test as $i=>$current_test) {
echo $current_test->is_palindrome() ? '<pre>Test '.($i+1).' is a palindrome.</pre>' : '<pre>Test '.($i+1).' is not a palindrome.</pre>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment