Created
March 15, 2012 20:08
-
-
Save madfriend/2046553 to your computer and use it in GitHub Desktop.
Lazy Strings class
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
<?php | |
// accepts default string and test function. | |
// test function is tweaked everytime object of class LazyStrings is casted to string, | |
// if test function returns FALSE/NULL default string is returned, otherwise the result of | |
// test. | |
class LazyString { | |
private $_default, $_tweak; | |
public function __construct($default_string, $tweak) { | |
list($this->_default, $this->_tweak) = array($default_string, $tweak); | |
} | |
public function __toString() { | |
if ($this->_tweak instanceof Closure) { | |
$result = call_user_func($this->_tweak); | |
return ($result!==NULL && $result!==FALSE) ? $result : $this->_default; | |
} | |
// TODO: accept callbacks in strings ('checkMyVariable') and arrays of | |
// two types: array($someObj, 'method') and array('someClass', 'someStaticMethod') | |
return $_default; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is extremely useful in the following case: