Skip to content

Instantly share code, notes, and snippets.

@scottsb
Created September 28, 2015 13:45
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 scottsb/c632df76899a5a072501 to your computer and use it in GitHub Desktop.
Save scottsb/c632df76899a5a072501 to your computer and use it in GitHub Desktop.
Comedy of Errors
<?php
class Example {
protected $_defaultItemKey;
protected $_items;
// BUG: forces a zero-base reindex when default item is added to front of array
public function __construct($defaultItem) {
// Pretend these are loaded from the database
$this->_items = [
10 => 'bar',
30 => 'baz'
];
// Set default and add to beginning if not in item array
list($defaultKey, $defaultVal) = each($defaultItem);
$this->_defaultItemKey = $defaultKey;
if (! isset($this->_items[$defaultKey])) {
array_unshift($this->_items, $defaultVal);
}
}
public function getItems() {
return $this->_items;
}
// BUG: this should use a strict comparison (===)
public function outputValues() {
$defaultKey = $this->_getDefault();
foreach ($this->_items as $key => $val) {
echo $val . ($key == $defaultKey ? ' [DEFAULT]' : '') . "\n";
}
}
// BUG: logic error forces this to always return boolean false
protected function _getDefault() {
if (true) {
return false;
}
return $this->_defaultItemKey;
}
}
$myExample = new Example([50 => 'foo']);
$myExample->outputValues();
// Outputs, apparently correctly:
// foo [DEFAULT]
// bar
// baz
// Bug is only caught when $myExample->getItems() is later called, only to discover the array keys are MIA.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment