Page 1 of 1

PHP String Object

Posted: Sun Feb 23, 2014 6:54 pm
by francoselem
Hello!
Do any of you know why we have not seen a more Object Oriented approach in PHP when it comes to Strings. It seems so reasonable to adopt a mechanism much like JavaScript's where every string is an object. For instance, I wrote a small little snippet that would highlight a few benefits when it comes to strings.

Code: Select all

class String {

	public $raw;

	public $htmlEntities;

	public $length;

	function __construct( $string ) {
		$this->raw = $string;
		$this->htmlEntities = htmlentities( $this->raw );
		$this->length = strlen( $this->raw );
	}

}
An object of this type would output the following

Code: Select all

object(String)[1]
	public 'raw' => string 'Hello, World' (length=12)
	public 'htmlEntities' => string 'Hello, World' (length=12)
	public 'length' => int 12
This way we wouldn't have to spend hours writing user defined functions like the amount of words in a string, or amount of occurrences of sub-strings that appear in a string object. Keep in mind this is a very quick example that I jotted down while writing the Snippet Master WordPress plugin, so my apologies if my point hasn't rendered distinguishable by that short snippet. Do any of you think something like this would be useful and worth developing further.

Please note that I have not done research on any possible PHP "String Objects" out there, I just sort of wanted to spectate feedback from this community.

Anyway, I appreciate any responses.

Re: PHP String Object

Posted: Mon Feb 24, 2014 3:44 pm
by VladSun
I'd rather see the String interface (no implementation) first.

Re: PHP String Object

Posted: Mon Feb 24, 2014 4:36 pm
by requinix
If you're talking about an official implementation, it's been talked about but puts people on edge as it starts changing the nature of the language itself. A related concept is autoboxing.

Unofficially? There are a lot of string functions to cover - make sure you cover all of them somehow, otherwise the inconsistency would drive people crazy. But a PHP solution means every string function call gets an additional function call, and the performance could be noticeable. IMO the best solution would have to be an extension, and one that's kept up to date whenever new string functions are added or old ones removed.

Re: PHP String Object

Posted: Mon Feb 24, 2014 7:33 pm
by Weirdan
This way we wouldn't have to spend hours writing user defined functions like the amount of words in a string, or amount of occurrences of sub-strings that appear in a string object.
You don't have to spend hours writing str_word_count() and substr_count(). They've been there for years.