tags:

views:

65

answers:

4

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?

A: 

Hi Shafee.

I'm afraid to tell you that you won't have any luck with either of both.
$str = new Str 'hello kitty'; will end up in fatal error and though the second method is valid it doesn't do what you intend but rather reassign a native string.

May I ask why you would want to have a wrapper araound a native type?

aefxx
yeah.. i didnt have any luck with either, therefore the question. I m interested in making my scripts a bit strongly typed.. a string should be a string and not an integer halfway into the script.
Shafee
A: 
  1. It's impossible to call functions in PHP without parentheses.
  2. Your next method will change the reference to string.

Why it doesn't look natural to you? It's the same way in Java.

You may find this useful:

php-string

Sagi
+2  A: 

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.

Gordon
looks like i av got to wait then..
Shafee
A: 

if you don't use paranthesis and quotes, PHP wil interpret it as a constant. There is no way of involving variables in the function. But you can do the following:

class String{ /*no __construct here*/ public $str; public getStr(){ return $this->str; } }

$s = new String; $s->str = "My string"; print $s->getStr();

but this doesn't make any sense. You should more focus on how your functions are functioning.

eyurdakul
Yeah.i knw. i also tried using __toString() magic method so that instead of print $s->getStr(); i could directly do print $s .. makes it a bit neater.
Shafee