function s($string) {
return new String($string);
}
class String
{
public $string;
public function __construct($string) {
$this->string = $string;
}
public function __toString() {
return $this->string;
}
// several helper methods like the following:
public function toLower() {
$this->string = strtolower($this->string);
return $this;
}
// this would create lots of extra objects,
// but leave the original unchanged
public function alternateToLower() {
return new String(strtolower($this->string));
}
}
$username = s('ExampleUser');
echo $username->toLower();
My concern would be the memory used to create several dozen extra objects. If this is indeed what you're talking about, is there any strong benefit besides convenience?Besides, most PHP code is linear without much looping other than iterating database records. The overhead of such an approach wouldn't matter that much, and when it does you can always use the old way of doing things.
But you wouldn't need to create an object per call, you could reuse a singleton that gets initialized by a wrapper function to work on your current variable (using references). Fix($str)->replace("foo", "bar") is a syntax that doesn't require object instantiation or string copying. And the singleton could use the mb functions internally to be multibyte aware.
Of course all of this is possible without creating a wrapper for vanilla strings.
How do you fix weak typing?
Also, i write php all day and i almost never run into bugs due to typing. You adopt some habits like always casting before use, and use an ide that warns you when you're doing stuff like using uninitialized variables (phpstorm is awesome), and the whole issue goes away for 95%. I'm not saying it doesn't cause bugs, just that i've found it to not be that big of a deal.
You could have something like jQuery's $ function, but for PHP variables, that gives you an OO api on top of that value (especially now that you can use the -> operator on return values of functions without intermediate assignment). I wonder why nobody's built that yet. I suppose because those in the PHP community are all busy programming instead of meta-programming.