Hai. I was making this simple string class and was wondering if there was a more natural way of doing it.
class Str{
function __construct($str){
$this->value = $str;
$this->length = strlen($str);
..
}
function __toString(){
return $this->value;
}
..
}
so now i have to use it like this:
$str = new Str('hello kitty');
echo $str;
But that doesnt look very 'natural' with the parentheses. So i was wondering if something like this, or similar was possible.
$str = new Str 'hello kitty'; # I dont believe this is possible although this is preferred.
$str = new Str; # get rid of the construct param.
$str = 'value here'; #instead of resetting, set 'value here' to Str::$value??
In the second method, is there a way i could possibly catch that variable bing set again and instead of reseting it, set this to Str::$value ? I have thought around and the closest i could come up to is the __destruct method. but there was no possible way to know how it was being destroyed. Is this possible or am i wasting my time?
Since PHP is loosely typed, there is no natural string class, because the natural way of using strings is, well, by just using them. However, as of PHP5.3 there is an extension in the SPL that provides strongly typed scalars:
However, keep in mind that this extension is marked experimental and subject to change. As of now, it is also not available on Windows.
You might also want to try https://github.com/nikic/scalar_objects
This extension implements the ability to register a class that handles the method calls to a certain primitive type (string, array, ...). As such it allows implementing APIs like $str->length().
Also See: https://github.com/alecgorge/PHP-String-Class
A good string class
Why it doesn't look natural to you? It's the same way in Java.
You may find this useful:
php-string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With