开发者

How to make a natural String class in PHP

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; # ge开发者_JS百科t 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:

  • http://php.net/manual/en/book.spl-types.php

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


  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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜