Hacker News new | past | comments | ask | show | jobs | submit login

Do you mean something like this?

  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?



Yes, lots of memory, much worse performance, but it doesn't really matter. If you care that much about those, you're not using any interpreted language.

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.


One reason to abstract away strings is that you can gain security. For example, your template might only accept an HTMLString, which can only be created from a String by escaping. Your database library might only accept a QueryEscapedString, and so on.

Of course all of this is possible without creating a wrapper for vanilla strings.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: